如何使用Python的with语句进行高效文件读写操作?

2026-06-09 18:472阅读0评论SEO基础
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计1467个文字,预计阅读时间需要6分钟。

如何使用Python的with语句进行高效文件读写操作?

原文示例讲述了Python打开文件、文件读写操作、with语句、文件常用函数等内容。以下是简化后的内容:

Python打开文件、读写操作、with语句、常用函数:- 打开文件:使用`open()`函数,例如`open('file.txt', 'r')`- 读写操作:使用`read()`、`write()`等- with语句:确保文件正确关闭,例如`with open('file.txt', 'r') as f:`- 常用函数:`readline()`、`readlines()`等

本文实例讲述了Python打开文件、文件读写操作、with方式、文件常用函数。分享给大家供大家参考,具体如下:

打开文件:

在python3中,打开文件的函数是:

open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True)

参数说明:

file--文件名

mode—打开模式,默认只读模式

buffering--如果buffering的值被设为0,就不会有寄存。如果buffering的值取1,访问文件时会寄存行。如果将buffering的值设为大于1的整数,表明了这就是的寄存区的缓冲大小。如果取负值,寄存区的缓冲大小则为系统默认。

encoding—打开文件的编码方式

模式介绍:

r:只读模式(默认)

w :只写模式,如果文件不存在就创建,如果存在,写入的数据会覆盖原来的数据

b :二进制模式

t :文本模式

+:可写可读模式

a:追加模式,如果文件存在则文件指针指向文件末尾(追加数据),如果不存在就创建

r+:读追加模式,先读,再追加

w+:写读模式,先写,意味着原本内容丢失,再读。

  • 如果对于含有非ascll字符的文件,必须使用encoding,否则会抛异常:

print("r".center(50,'-')) f=open("file.txt",encoding="utf-8") print(f.read()) f.close() ----------------- 运行结果: my sas aaa fsafsa 中文 中文 葫芦娃

文件使用完毕后必须关闭: 文件指针.close()


文件操作:

读操作:

读取文件内容如下:

  • reads()是读出全部内容

print("r".center(50,'-')) f=open("file.txt",encoding="utf-8") print(f.read()) f.close() --------------------------- 运行结果: my sas aaa fsafsa 中文 中文 葫芦娃

  • readline()是读出一行

print("r".center(50,'-')) f=open("file.txt",encoding="utf-8") print(f.readline()) f.close() ----------- 运行结果: my

  • readlines()是读出全部内容,并整理成一个列表

print("r".center(50,'-')) f=open("file.txt",encoding="utf-8") print(f.readlines()) f.close() #------------------------r------------------------- #运行结果: ['my\n', 'sas\n', 'aaa\n', 'fsafsa\n', '中文\n', '中文\n', '葫芦娃\n', '\n']

  • r+模式会根据读的内容来决定指针的位置

print("r".center(50,'-')) f=open("file.txt","r+",encoding="utf-8") # print(f.readline()) f.write("hello mike") f.close()

结果:

print("r".center(50,'-')) f=open("file.txt","r+",encoding="utf-8") print(f.readline()) f.write("hello mike") f.close()

新结果:

写操作:

  • write():将一个字符串写入文件

myfile=open("myfile1","wb") myfile.write(b"nnnnnn") myfile.write("my葫芦娃".encode("utf-8")) myfile.close()

  • writelines(可迭代对象) 将一个可迭代对象写入文件

myfile=open("myfile1","wb") myfile.write(b"nnnnnn") myfile.writelines([b'1',b'2',b'3',b'4']) myfile.close()

  • 当需要写完之后即时读出来时,使用w+,然后将文件指针置回文件头:

myfile=open("myfile1","wb+") myfile.write(b"nnnnnn") myfile.seek(0) print(myfile.read()) myfile.close()

      • 如果是需要读出特定位置,可以使用变量来记录位置

myfile=open("myfile1","wb+") myfile.write(b"1nnnnnn") site=myfile.tell() myfile.write(b"2nnnnnn") myfile.seek(site)##读出后一段 print(myfile.read()) myfile.close()


with:

  • 为了便捷的关闭文件,python增加了with功能,当with体执行完将自动关闭打开的文件:

with open("file.txt","r+",encoding="utf-8") as f:##将自动执行f.close() print(f.tell()) f.write("金刚") for line in f: print(line,end="")

  • 可以同时打开多个文件:

with open("file.txt",'r') as f ,\ open("file.new",'r') as m: print(f.read(),m.read())


文件常用函数:

file.close():关闭文件。关闭后文件不能再进行读写操作

file.seek(offset[, whence]):设置文件当前位置

file.tell():返回文件当前位置。

myfile=open("myfile1","wb+") myfile.write(b"1nnnnnn") site=myfile.tell() myfile.write(b"2nnnnnn") myfile.seek(site)##读出后一段 print(myfile.read()) myfile.close()

file.flush():刷新文件内部缓冲,立即把内部缓冲区的数据写入文件,因为并不是马上将文件

import time myfile=open("myfile1","wb+") myfile.write(b"1nnnnnn") time.sleep(10) # myfile.flush() myfile.write(b"2nnnnnn") myfile.close()

上述代码,直到程序运行完成才一次性写入“1nnnnnn2nnnnnn”

import time myfile=open("myfile1","wb+") myfile.write(b"1nnnnnn") myfile.flush() time.sleep(10) myfile.write(b"2nnnnnn") myfile.close()

上述代码,可以看到,在程序sleep之前就已经写入了“1nnnnnn”

file.truncate([size]):截取文件,从文件开头,截到指定位置,会覆盖原文件。

文件内容:

如何使用Python的with语句进行高效文件读写操作?

print("r".center(50,'-')) f=open("file.txt","r+",encoding="utf-8") print(f.readline()) print("----truncate()-------") print(f.tell()) m=f.tell() f.truncate(m)#内容从0位置截断到指定位置,不论当前光标位置 f.close()

执行后,文件内容:

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python文件与目录操作技巧汇总》、《Python文本文件操作技巧汇总》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》

希望本文所述对大家Python程序设计有所帮助。

本文共计1467个文字,预计阅读时间需要6分钟。

如何使用Python的with语句进行高效文件读写操作?

原文示例讲述了Python打开文件、文件读写操作、with语句、文件常用函数等内容。以下是简化后的内容:

Python打开文件、读写操作、with语句、常用函数:- 打开文件:使用`open()`函数,例如`open('file.txt', 'r')`- 读写操作:使用`read()`、`write()`等- with语句:确保文件正确关闭,例如`with open('file.txt', 'r') as f:`- 常用函数:`readline()`、`readlines()`等

本文实例讲述了Python打开文件、文件读写操作、with方式、文件常用函数。分享给大家供大家参考,具体如下:

打开文件:

在python3中,打开文件的函数是:

open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True)

参数说明:

file--文件名

mode—打开模式,默认只读模式

buffering--如果buffering的值被设为0,就不会有寄存。如果buffering的值取1,访问文件时会寄存行。如果将buffering的值设为大于1的整数,表明了这就是的寄存区的缓冲大小。如果取负值,寄存区的缓冲大小则为系统默认。

encoding—打开文件的编码方式

模式介绍:

r:只读模式(默认)

w :只写模式,如果文件不存在就创建,如果存在,写入的数据会覆盖原来的数据

b :二进制模式

t :文本模式

+:可写可读模式

a:追加模式,如果文件存在则文件指针指向文件末尾(追加数据),如果不存在就创建

r+:读追加模式,先读,再追加

w+:写读模式,先写,意味着原本内容丢失,再读。

  • 如果对于含有非ascll字符的文件,必须使用encoding,否则会抛异常:

print("r".center(50,'-')) f=open("file.txt",encoding="utf-8") print(f.read()) f.close() ----------------- 运行结果: my sas aaa fsafsa 中文 中文 葫芦娃

文件使用完毕后必须关闭: 文件指针.close()


文件操作:

读操作:

读取文件内容如下:

  • reads()是读出全部内容

print("r".center(50,'-')) f=open("file.txt",encoding="utf-8") print(f.read()) f.close() --------------------------- 运行结果: my sas aaa fsafsa 中文 中文 葫芦娃

  • readline()是读出一行

print("r".center(50,'-')) f=open("file.txt",encoding="utf-8") print(f.readline()) f.close() ----------- 运行结果: my

  • readlines()是读出全部内容,并整理成一个列表

print("r".center(50,'-')) f=open("file.txt",encoding="utf-8") print(f.readlines()) f.close() #------------------------r------------------------- #运行结果: ['my\n', 'sas\n', 'aaa\n', 'fsafsa\n', '中文\n', '中文\n', '葫芦娃\n', '\n']

  • r+模式会根据读的内容来决定指针的位置

print("r".center(50,'-')) f=open("file.txt","r+",encoding="utf-8") # print(f.readline()) f.write("hello mike") f.close()

结果:

print("r".center(50,'-')) f=open("file.txt","r+",encoding="utf-8") print(f.readline()) f.write("hello mike") f.close()

新结果:

写操作:

  • write():将一个字符串写入文件

myfile=open("myfile1","wb") myfile.write(b"nnnnnn") myfile.write("my葫芦娃".encode("utf-8")) myfile.close()

  • writelines(可迭代对象) 将一个可迭代对象写入文件

myfile=open("myfile1","wb") myfile.write(b"nnnnnn") myfile.writelines([b'1',b'2',b'3',b'4']) myfile.close()

  • 当需要写完之后即时读出来时,使用w+,然后将文件指针置回文件头:

myfile=open("myfile1","wb+") myfile.write(b"nnnnnn") myfile.seek(0) print(myfile.read()) myfile.close()

      • 如果是需要读出特定位置,可以使用变量来记录位置

myfile=open("myfile1","wb+") myfile.write(b"1nnnnnn") site=myfile.tell() myfile.write(b"2nnnnnn") myfile.seek(site)##读出后一段 print(myfile.read()) myfile.close()


with:

  • 为了便捷的关闭文件,python增加了with功能,当with体执行完将自动关闭打开的文件:

with open("file.txt","r+",encoding="utf-8") as f:##将自动执行f.close() print(f.tell()) f.write("金刚") for line in f: print(line,end="")

  • 可以同时打开多个文件:

with open("file.txt",'r') as f ,\ open("file.new",'r') as m: print(f.read(),m.read())


文件常用函数:

file.close():关闭文件。关闭后文件不能再进行读写操作

file.seek(offset[, whence]):设置文件当前位置

file.tell():返回文件当前位置。

myfile=open("myfile1","wb+") myfile.write(b"1nnnnnn") site=myfile.tell() myfile.write(b"2nnnnnn") myfile.seek(site)##读出后一段 print(myfile.read()) myfile.close()

file.flush():刷新文件内部缓冲,立即把内部缓冲区的数据写入文件,因为并不是马上将文件

import time myfile=open("myfile1","wb+") myfile.write(b"1nnnnnn") time.sleep(10) # myfile.flush() myfile.write(b"2nnnnnn") myfile.close()

上述代码,直到程序运行完成才一次性写入“1nnnnnn2nnnnnn”

import time myfile=open("myfile1","wb+") myfile.write(b"1nnnnnn") myfile.flush() time.sleep(10) myfile.write(b"2nnnnnn") myfile.close()

上述代码,可以看到,在程序sleep之前就已经写入了“1nnnnnn”

file.truncate([size]):截取文件,从文件开头,截到指定位置,会覆盖原文件。

文件内容:

如何使用Python的with语句进行高效文件读写操作?

print("r".center(50,'-')) f=open("file.txt","r+",encoding="utf-8") print(f.readline()) print("----truncate()-------") print(f.tell()) m=f.tell() f.truncate(m)#内容从0位置截断到指定位置,不论当前光标位置 f.close()

执行后,文件内容:

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python文件与目录操作技巧汇总》、《Python文本文件操作技巧汇总》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》

希望本文所述对大家Python程序设计有所帮助。