search
HomeBackend DevelopmentPython TutorialPython编程中的文件读写及相关的文件对象方法讲解

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

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
详细讲解Python之Seaborn(数据可视化)详细讲解Python之Seaborn(数据可视化)Apr 21, 2022 pm 06:08 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于Seaborn的相关问题,包括了数据可视化处理的散点图、折线图、条形图等等内容,下面一起来看一下,希望对大家有帮助。

详细了解Python进程池与进程锁详细了解Python进程池与进程锁May 10, 2022 pm 06:11 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于进程池与进程锁的相关问题,包括进程池的创建模块,进程池函数等等内容,下面一起来看一下,希望对大家有帮助。

Python自动化实践之筛选简历Python自动化实践之筛选简历Jun 07, 2022 pm 06:59 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于简历筛选的相关问题,包括了定义 ReadDoc 类用以读取 word 文件以及定义 search_word 函数用以筛选的相关内容,下面一起来看一下,希望对大家有帮助。

归纳总结Python标准库归纳总结Python标准库May 03, 2022 am 09:00 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于标准库总结的相关问题,下面一起来看一下,希望对大家有帮助。

分享10款高效的VSCode插件,总有一款能够惊艳到你!!分享10款高效的VSCode插件,总有一款能够惊艳到你!!Mar 09, 2021 am 10:15 AM

VS Code的确是一款非常热门、有强大用户基础的一款开发工具。本文给大家介绍一下10款高效、好用的插件,能够让原本单薄的VS Code如虎添翼,开发效率顿时提升到一个新的阶段。

Python数据类型详解之字符串、数字Python数据类型详解之字符串、数字Apr 27, 2022 pm 07:27 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于数据类型之字符串、数字的相关问题,下面一起来看一下,希望对大家有帮助。

详细介绍python的numpy模块详细介绍python的numpy模块May 19, 2022 am 11:43 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于numpy模块的相关问题,Numpy是Numerical Python extensions的缩写,字面意思是Python数值计算扩展,下面一起来看一下,希望对大家有帮助。

python中文是什么意思python中文是什么意思Jun 24, 2019 pm 02:22 PM

pythn的中文意思是巨蟒、蟒蛇。1989年圣诞节期间,Guido van Rossum在家闲的没事干,为了跟朋友庆祝圣诞节,决定发明一种全新的脚本语言。他很喜欢一个肥皂剧叫Monty Python,所以便把这门语言叫做python。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.