Python中text文件操作

Python中text文件操作1 打开一个文件 open handle open filename mode mode 为文件打开的模式 r 表示只读 w 表示可写 rb 表示二进制只读格式 wb 表示二进制可写格式 默认是只读模式 open 函数返回一个 file handle 文件句柄 可以将之视为一系列的行

大家好,我是讯享网,很高兴认识大家。

1、打开一个文件open()
handle=open(filename,mode)
mode为文件打开的模式,‘r’表示只读,’w’表示可写,‘rb’表示二进制只读格式,’wb’表示二进制可写格式,默认是只读模式。
open()函数返回一个file handle(文件句柄),可以将之视为一系列的行。

handle=open('temp.txt')#返回文件句柄 for i in handle: print(i) 

讯享网

this is second line

讯享网handle=open('temp.txt') for i in handle: print(i.strip()) 

输出:
this is first line
this is second line
this is third line
2、读取一个文件read()
对open()函数返回的file handle(文件句柄)执行读取操作,能够读取的前提条件是open()的mode是‘r’(只读)而不是’w’(可写)。

file=open('temp.txt') print(file.read()) 

输出:
this is first line
this is second line
this is third line
3、文件写入write()
对open()函数返回的file handle(文件句柄)执行写入操作,能够写入的前提条件是open()的mode是’w’(可写)而不是‘r’(只读)。如果原文件中有内容,write()默认擦除原文件中的内容再执行写入操作。


讯享网

讯享网#对一个空文件执行写入操作 handle=open('temp.txt','w')#以可写模式打开文件 handle.write('\nthis is the third line') handle.write('\nthis is the forth line') handle.close()#close()在这里相当于’save'操作 

写入后的文件如下图所示:
在这里插入图片描述

#将from_file文件中的内容写入到to_file文件中 handle=open('to_file.txt','w') handle.write(open('from_file.txt').read()) handle.close() 

4、文件清空truncate()
对open()函数返回的file handle(文件句柄)执行文件清空操作,能够清空的前提条件是open()的mode是’w’(可写)而不是‘r’(只读)。该命令要谨慎使用!

讯享网handle=open('temp.txt','w') handle.truncate() handle.close() 

5、移动文件读取指针到指定位置seek()
对open()函数返回的file handle(文件句柄)执行指针移动操作
seek(offset[, whence])
offset:需要移动偏移的字节数
whence:可选,默认为0,代表从文件头开始偏移;1代表从当前位置开始偏移;2代表从文件末尾开始偏移。
seek(0)命令在很多文件处理中必不可少,因为如果已经执行完read()后,文件的读取指针已经在文件的末尾。接下来继续执行read()或者readline(),如果不将读取指针重置到文件开头,read()或者readline()读取出来的内容都是空。

handle=open('temp.txt') handle.read() 

输出:‘this is test\n2 test\n3 test’

讯享网handle.seek(0) handle.readline() 

输出:‘this is test\n’

6、读取文件中的一行readline()
对open()函数返回的file handle(文件句柄)执行行读取操作,这里每次执行完后,文件的读取指针后移一行,多次执行该命令,可以按行读取文件。

小讯
上一篇 2025-03-16 08:46
下一篇 2025-01-28 08:18

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/123254.html