搜索
首页后端开发Python教程Python编程中的文件读写及相关的文件对象方法讲解

python文件读写

python 进行文件读写的内建函数是open或file

file_hander(文件句柄或者叫做对象)= open(filename,mode)

mode:

模式    说明

r        只读

r+      读写

w       写入,先删除源文件,在重新写入,如果文件没有则创建

w+     读写,先删除源文件,在重新写入,如果文件没有则创建(可以写入写出)

读文件:

>>> fo = open("/root/a.txt")
>>> fo
<open file '/root/a.txt', mode 'r' at 0x7f5095dec4e0>
>>> fo.read()
'hello davehe\ni am emily\nemily emily\n'
>>> fo.close()
>>> fo.read()                     #对象已关闭,在读取就读不到
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
ValueError: I/O operation on closed file

 

>>> f1 = file("/root/a.txt")         
>>> f1.read()
'hello davehe\ni am emily\nemily emily\n'
>>> f1.close()

写文件:

root@10.1.6.200:~# ls -l new.txt
ls: cannot access new.txt: No such file or directory
>>> fnew = open("/root/new.txt",'w')  w参数文件没有则创建
>>> fnew.write('hello \n i am dave')

这时查看文件数据其实还只是在缓存区中,没有真正落到文件上.

root@10.1.6.200:~# cat new.txt 
root@10.1.6.200:~#

只要我把文件关闭,数据会从缓存区写到文件里

>>> fnew.close()
root@10.1.6.200:~# cat new.txt 
hello 
i am dave

再次使用w参数,文件会被清空,所以用该参数需要谨慎.

>>> fnew = open("/root/new.txt","w")
root@10.1.6.200:~# cat new.txt 
root@10.1.6.200:~#

mode使用r+参数:

>>> fnew = open("/root/new.txt",'r+')
>>> fnew.read()
'hello dave'
>>> fnew.write('i am dave')
>>> fnew.close()
root@10.1.6.200:~# cat new.txt 
hello davei am dave

这次打开文件,直接写入,会发现ooo替换开头字母,因为上面读取操作使用了指针在写就写在后面.而这次是直接从头写入.

>>> fnew = open("/root/new.txt",'r+')
>>> fnew.write('ooo')
>>> fnew.close()
root@10.1.6.200:~# cat new.txt 
ooolo davei am dave

文件对象方法
下面文件对象方法

  • FileObject.close()
  • String=FileObject.readline([size])
  • List = FileObject.readlines([size])
  • String = FileObject.read([size])   read:读取所有数据
  • FileObject.next()          
  • FileObject.write(string)
  • FileObject.writelines(List)
  • FlieObject.seek(偏移量,选项)
  • FlieObject.flush() 提交更新
>>> for i in open("/root/a.txt"):  用open可以返回迭代类型的变量,可以逐行读取数据
...   print i
... 
hello davehe
i am emily
emily emily

FileObject.readline: 每次读取文件的一行,size是指每行每次读取size个字节,直到行的末尾,超出范围会读取空字符串

>>> f1 = open("/root/a.txt")
>>> f1.readline()
'hello davehe\n'
>>> f1.readline()
'i am emily\n'
>>> f1.readline()
'emily emily\n'
>>> f1.readline()
''
>>> f1.readline()
''
>>>f1.close()

 FileObject.readlines:返回一个列表

>>> f1 = open("/root/a.txt")
>>> f1.readlines()
['hello davehe\n', 'i am emily\n', 'emily emily\n']''

FileObject.next:返回当前行,并将文件指针到下一行,超出范围会给予警示,停止迭代.

>>> f1 = open("/root/a.txt")
>>> f1.next()
'hello davehe\n'
>>> f1.next()
'i am emily\n'
>>> f1.next()
'emily emily\n'
>>> f1.next()
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
StopIteration

FileObject.write:write和后面writelines在写入前会是否清除文件中原来所有的数据,在重新写入新的内容,取决于打开文件的模式.

FileObject.writelines(List):多行写,效率比write高,速度更快,少量写入可以使用write

>>> l = ["python\n","python\n","python\n"]
>>> f1 = open('/root/a.txt','a')
>>> f1.writelines(l)
>>> f1.close()
root@10.1.6.200:~# cat a.txt 
hello davehe
i am emily
emily emily
python
python
python

FlieObject.seek(偏移量,选项):可以在文件中移动文件指针到不同的位置.

位置的默认值为0,代表从文件开头算起(即绝对偏移量),1代表从当前位置算起,2代表从文件末尾算起.

>>> f1 = open('/root/a.txt','r+')
>>> f1.read()
'hello davehe\ni am emily\nemily emily\npython\npython\npython\n'
>>> f1.seek(0,0)   指针指到开头,在读
>>> f1.read()
'hello davehe\ni am emily\nemily emily\npython\npython\npython\n'
>>> f1.read()
''
>>> f1.seek(0,0)
>>> f1.seek(0,2)   指针指到末尾,在读
>>> f1.read()
''

下面看个小实例,查找a.txt中emily出现几次

root@10.1.6.200:~# vim file.py 
#!/usr/bin/env python
import re
f1 = open('/root/a.txt')
count = 0
for s in f1.readlines():
  li = re.findall("emily",s)
  if len(li) > 0:
    count = count + len(li)
print "this is have %d emily" % count 
f1.close()
root@10.1.6.200:~# cat a.txt 
hello davehe
i am emily
emily emily
root@10.1.6.200:~# python file.py 
this is have 3 emily

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
Python:深入研究汇编和解释Python:深入研究汇编和解释May 12, 2025 am 12:14 AM

pythonisehybridmodelofcompilationand interpretation:1)thepythoninterspretercompilesourcececodeintoplatform- interpententbybytecode.2)thepytythonvirtualmachine(pvm)thenexecuteCutestestestesteSteSteSteSteSteSthisByTecode,BelancingEaseofuseWithPerformance。

Python是一种解释或编译语言,为什么重要?Python是一种解释或编译语言,为什么重要?May 12, 2025 am 12:09 AM

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允许fordingfordforderynamictynamictymictymictymictyandrapiddefupment,尽管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

对于python中的循环时循环与循环:解释了关键差异对于python中的循环时循环与循环:解释了关键差异May 12, 2025 am 12:08 AM

在您的知识之际,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations则youneedtoloopuntilaconditionismet

循环时:实用指南循环时:实用指南May 12, 2025 am 12:07 AM

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond

Python:它是真正的解释吗?揭穿神话Python:它是真正的解释吗?揭穿神话May 12, 2025 am 12:05 AM

pythonisnotpuroly interpred; itosisehybridablectofbytecodecompilationandruntimeinterpretation.1)PythonCompiLessourceceCeceDintobyTecode,whitsthenexecececected bytybytybythepythepythepythonvirtirtualmachine(pvm).2)

与同一元素的Python串联列表与同一元素的Python串联列表May 11, 2025 am 12:08 AM

concateNateListsinpythonwithTheSamelements,使用:1)operatototakeepduplicates,2)asettoremavelemavphicates,or3)listCompreanspearensionforcontroloverduplicates,每个methodhasdhasdifferentperferentperferentperforentperforentperforentperfortenceandordormplications。

解释与编译语言:Python的位置解释与编译语言:Python的位置May 11, 2025 am 12:07 AM

pythonisanterpretedlanguage,offeringosofuseandflexibilitybutfacingperformancelanceLimitationsInCricapplications.1)drightingedlanguageslikeLikeLikeLikeLikeLikeLikeLikeThonexecuteline-by-line,允许ImmediaMediaMediaMediaMediaMediateFeedBackAndBackAndRapidPrototypiD.2)compiledLanguagesLanguagesLagagesLikagesLikec/c thresst

循环时:您什么时候在Python中使用?循环时:您什么时候在Python中使用?May 11, 2025 am 12:05 AM

Useforloopswhenthenumberofiterationsisknowninadvance,andwhileloopswheniterationsdependonacondition.1)Forloopsareidealforsequenceslikelistsorranges.2)Whileloopssuitscenarioswheretheloopcontinuesuntilaspecificconditionismet,usefulforuserinputsoralgorit

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!

MinGW - 适用于 Windows 的极简 GNU

MinGW - 适用于 Windows 的极简 GNU

这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能