suchen
HeimBackend-EntwicklungPython-TutorialPython 文件和输入输出小结

1.打开和关闭文件(open(),file(),close())

有两种内建函数可以获取文件对象:open和file。他们的用法完全一样。下面只以open()为例子讲解。获取一个文件对象(打开文件)的语法如下:       

代码如下:

fileObj = open(filename,access_mode='r',buffering=-1) 

filename不用说你也应该知道是你要打开文件的路径。
access_mode用来标识文件打开的模式,默认为r(只读)。

常用的模式如下表所示:

文件模式 解释
r 以只读方式打开
w 以写方式打开,文件不为空时清空文件;文件不存在时新建文件。
a 追加模式,没有则创建
r+,w+,a+ 以读写模式打开,参见w,a

另外还有一个b表示二进制模式访问,但是对于Linux或者unix系统来说这个模式没有任何意义,因为他们把所有文件都看作二进制文件,包括文本文件。


第三个参数不经常用到,标识访问文件的缓冲方式,0代表不缓冲,1代表缓
冲一行,-1代表使用系统默认缓冲方式。只要使用系统默认就好。

一些例子:

代码如下:


>>> f = open('/etc/passwd','r')
>>> f1 = open('/etc/test','w')

使用完文件后,一定要记得关闭文件,操作如下:

代码如下:


>>> f.close()

2.文件读入

2.1.file.read(size = -1)
    读取从当前文件游标起size个字节的文件内容。如果size=-1,则读取所有剩余字节。

代码如下:


>>> f = open('/etc/passwd')
>>> f.read(100)
'root:x:0:0:root:/root:/bin/bash\nbin:x:1:1:bin:/bin:/sbin/nologin\ndaemon:x:2:2:daemon:/sbin:/sbin/nol'

2.2.file.readlines(size=-1)

    从文件中读取并返回一行(包括行结束符),或返回最大size个字符

代码如下:


>>> f.readline()
'ogin\n'#和上面一个例子输出的最后拼起来就是  'nologin',因为游标在l后面。
>>> f.readline(1)
'a'

2.3.file.readlines(sizhint=0)
    读取文件所有的行,并作为一个列表返回(包括行结束符),如果sizhint>0则返回总和大约sizhint字节的行(具体由缓冲区大小决定)。

代码如下:


f.readlines()
['dm:x:3:4:adm:/var/adm:/sbin/nologin\n', 'lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin\n', 'sync:x:5:0:sync:/sbin:/bin/sync\n', 'shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown\n', 'halt:x:7:0:halt:/sbin:/sbin/halt\n', 'mail:x:8:12:mail:/var/spool/mail:/sbin/nologin\n', ......

输出省略。

3.文件输出

3.1.file.write(str)
    向文件中写入指定的字符串。

代码如下:


>>> f = file('/root/test.py','w+')
>>> f.write("print 'hello,world'")
>>> f.read()
''
>>> f.close()
>>> file('/root/test.py','r').read()
"print 'hello,world'"

3.2.file.write(seq)

    向文件写入字符串序列seq。seq是任何返回字符串的可迭代对象。

代码如下:


>>> f = file('/root/test.py','a+')
>>> codelst = ['\n','import os\n',"os.popen('ls').read()\n"]
>>> f.writelines(codelst)
>>> f.close()
>>> file('/root/test.py','r').read()
"print 'hello,world'\nimport os\nos.popen('ls').read()\n"

注意,文件写入的时候,不会自动加上换行符,必须手动加上。

4.文件移动

    学过C语言的同学,一定对fseek()函数不陌生,在Python中,seek()方法是fseek()的替代者。

    seek(offset,whence=0)
    方法可以将文件游标移动到文件的任意位置。其中offset代表需要移动的偏移字节数,whence表示要从哪个位置开始偏移:
    0代表从文件开头开始算起,
    1代表从当前位置开始算起,
    2代表从文件末尾算起。

    那我们如何知道当前文件游标在哪里呢?别担心,这里有个tell()方法可以返回当前文件游标的位置。

5.文件迭代

    在Python中,文件不仅仅是一个对象,而且是一个可迭代对象!我们可以利用如下迭代方式,轻松的访问和处理文件内容,而不必全部读出(readlines)后再迭代(性能上差了很多哦!)

代码如下:


for eachline in f:
    #dealwith eachline of f

例如:

代码如下:


>>> for eachline in f:
...     print eachline

6.os、os.path与文件

os和os.path中提供了一些跟文件有关的接口,下面介绍一些常用的接口。其他接口可以自己查阅相关文档。

注意:以下函数传入的参数都是字符串形式的文件名字,文件名可由文件对象的name属性获得。

函数 描述
os.path.basename() 去掉目录路径,返回文件名
os.path.dirname() 去掉文件名,返回目录路径
os.path.getatime()
os.path.getctime()
os.path.getmtime()
os.path.size()
返回文件的atime,ctime,mtime和大小
os.path.exists() 该文件或目录是否存在
os.path.abs() 指定路径是否为绝对路径
os.path.isdir() 路径是否存在且为目录
os.path.isfile() 路径是否存在且为文件。
os.path.islink() 指定路径是否存在且为一个符号链接

代码如下:


>>> import os.path
>>> f = open('/root/test.py','r')
>>> os.path.basename(f.name)
'test.py'
>>> f.name
'/root/test.py'
>>> os.path.getsize(f.name)
52
>>> os.path.isabs(f.name)
True
>>> os.path.isdir(f.name)
False

Stellungnahme
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Python: Ein tiefes Eintauchen in Zusammenstellung und InterpretationPython: Ein tiefes Eintauchen in Zusammenstellung und InterpretationMay 12, 2025 am 12:14 AM

PythonusesahybridmodelofCompilation und Interpretation: 1) thepythonInterPreterCompilessourceCodeIntoplatform-unintenpendentBytecode.2) Thepythonvirtualmachine (PVM) ThenexexexexecthisByTeCode, BalancingeAnsewusewithperformance.

Ist Python eine interpretierte oder eine kompilierte Sprache, und warum ist es wichtig?Ist Python eine interpretierte oder eine kompilierte Sprache, und warum ist es wichtig?May 12, 2025 am 12:09 AM

Pythonisbothinterpreted und kompiliert.1) ItscompiledToByteCodeForPortabilityAcrossplatform.2) thytecodeTheninterpreted, und das ErlaubnisfordyNamictyPingandRapidDevelopment zulässt, obwohl es sich

Für Schleife vs während der Schleife in Python: Schlüsselunterschiede erklärtFür Schleife vs während der Schleife in Python: Schlüsselunterschiede erklärtMay 12, 2025 am 12:08 AM

ForloopsaridealWenyouKnowtHenumberofofiterationssinadvance, während whileloopsarebetterForsituationswhereyouneedtoloopuntilaconditionismet.forloopsaremoreffictionAndable, geeigneter Verfaserungsverlust, whereaswiloopsofofermorcontrolanduseusefulfulf

Für und während Schleifen: ein praktischer LeitfadenFür und während Schleifen: ein praktischer LeitfadenMay 12, 2025 am 12:07 AM

Forloopsareusedwhenthenumberofiterationsisknowninadvance,whilewhileloopsareusedwhentheiterationsdependonacondition.1)Forloopsareidealforiteratingoversequenceslikelistsorarrays.2)Whileloopsaresuitableforscenarioswheretheloopcontinuesuntilaspecificcond

Python: Ist es wirklich interpretiert? Die Mythen entlarvenPython: Ist es wirklich interpretiert? Die Mythen entlarvenMay 12, 2025 am 12:05 AM

Pythonisnotpurelyinterpretiert; itusesahybridapproachofByteCodecompilation undruntimeinterpretation.1) PythoncompilessourcecodeIntoBytecode, die ISthenexecutBythepythonvirtualmachine (Pvm)

Python -Verkettungslisten mit demselben ElementPython -Verkettungslisten mit demselben ElementMay 11, 2025 am 12:08 AM

ToconcatenatelistsinpythonWithThesameElements, Verwendung: 1) Die Operatortokeepduplikate, 2) asettoremoveduplicate, or3) listenConpRectionforControloverDuplikate, EvermethodhasDifferentPerformanceInDormplocate.

Interpretiert gegen kompilierte Sprachen: Pythons PlatzInterpretiert gegen kompilierte Sprachen: Pythons PlatzMay 11, 2025 am 12:07 AM

PythonisaninterpretedLuage, OfferingaseofuseandflexibilitätsbutfacingPerformancelimitationsincriticalApplications.1) InterpretedLanguages ​​LikePythonexecutine-by-Line, ermöglicht, dassmediateFeedbackandrapidPrototyping.2) CompiledLanguagesslikec/C.5.

Für und während der Schleifen: Wann benutzt du jeweils in Python?Für und während der Schleifen: Wann benutzt du jeweils in Python?May 11, 2025 am 12:05 AM

Useforloopswhenthenumberofofiterationssisknowninadvance und wileloopswhenCiterationsDependonacondition.1) Forloopsardealforsequencelistorranges.2) Während

See all articles

Heiße KI -Werkzeuge

Undresser.AI Undress

Undresser.AI Undress

KI-gestützte App zum Erstellen realistischer Aktfotos

AI Clothes Remover

AI Clothes Remover

Online-KI-Tool zum Entfernen von Kleidung aus Fotos.

Undress AI Tool

Undress AI Tool

Ausziehbilder kostenlos

Clothoff.io

Clothoff.io

KI-Kleiderentferner

Video Face Swap

Video Face Swap

Tauschen Sie Gesichter in jedem Video mühelos mit unserem völlig kostenlosen KI-Gesichtstausch-Tool aus!

Heißer Artikel

Nordhold: Fusionssystem, erklärt
3 Wochen vorBy尊渡假赌尊渡假赌尊渡假赌
Mandragora: Flüstern des Hexenbaum
3 Wochen vorBy尊渡假赌尊渡假赌尊渡假赌

Heiße Werkzeuge

Sicherer Prüfungsbrowser

Sicherer Prüfungsbrowser

Safe Exam Browser ist eine sichere Browserumgebung für die sichere Teilnahme an Online-Prüfungen. Diese Software verwandelt jeden Computer in einen sicheren Arbeitsplatz. Es kontrolliert den Zugriff auf alle Dienstprogramme und verhindert, dass Schüler nicht autorisierte Ressourcen nutzen.

Herunterladen der Mac-Version des Atom-Editors

Herunterladen der Mac-Version des Atom-Editors

Der beliebteste Open-Source-Editor

SublimeText3 chinesische Version

SublimeText3 chinesische Version

Chinesische Version, sehr einfach zu bedienen

WebStorm-Mac-Version

WebStorm-Mac-Version

Nützliche JavaScript-Entwicklungstools

Dreamweaver Mac

Dreamweaver Mac

Visuelle Webentwicklungstools