文章目录

  • ​​1 读文件​​
  • ​​1.1 使用open()和close()​​
  • ​​1.2 使用with open()​​
  • ​​2 写文件​​
  • ​​2.1 字符编码​​
  • ​​2.2 读写方式列表​​
  • ​​2.3 file object的属性​​

1 读文件

1.1 使用open()和close()

使用Python内置的open()函数,传入文件名和标示符:

>>> f=open(r'F:\jupyter notebook files\text files.txt','r') #标示符'r'表示读

如果文件不存在,open()函数就会抛出一个错误,并且给出错误码和详细的信息告诉你文件不存在:

>>> f=open(r'F:\jupyter notebook files\text.txt','r')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'F:\\jupyter notebook files\\text.txt'

调用read()方法可以一次读取文件的全部内容,Python把内容读到内存,用一个str对象表示:

>>> contents=f.read()
>>> print(contents)
naruto
bleach
onepiece

最后需要调用close()方法关闭文件。文件使用完毕后必须关闭,因为文件对象会占用操作系统的资源,并且操作系统同一时间能打开的文件数量也是有限的:

>>> f.close()

由于文件读写时都有可能产生IOError,一旦出错,后面的f.close()就不会调用。为了保证无论是否出错都能正确地关闭文件,我们可以使用try … finally来实现:

try:
f=open(r'F:\jupyter notebook files\text files.txt','r')
contents=f.read()
print(contents)
finally:
if f:
f.close()

输出如下:

naruto
bleach
onepiece

1.2 使用with open()

每次都写close()比较繁琐,Python引入with语句,这样能够确保最后文件一定被关闭,且不用手动再调用close方法,效果和前面的try … finally是一样的。

注意:

  • 1、调用read()会一次性读取文件的全部内容
with open(r'F:\jupyter notebook files\text files.txt','r') as f:
contents=f.read()
print(contents)

输出如下:

naruto
bleach
onepiece
  • 2、调用readline()可以每次读取一行内容
with open(r'F:\jupyter notebook files\text files.txt','r') as f:
a=f.readline()
print(a)

b=f.readline()
print(b)

c=f.readline()
print(c)

输出如下:

naruto

bleach

onepiece
  • 3、调用readlines()一次读取所有内容并按行返回list
with open(r'F:\jupyter notebook files\text files.txt','r') as f:
a=f.readlines()
print(a)

输出如下:

['naruto\n', 'bleach\n', 'onepiece']

2 写文件

调用open()函数时,传入标识符’w’或者’wb’表示写文本文件或写二进制文件:

with open(r'F:\jupyter notebook files\text files.txt','w') as f:
a=f.write('attack on titan\n')

要写入特定编码的文本文件,请给open()函数传入encoding参数,将字符串自动转换成指定编码。

2.1 字符编码

要读取非UTF-8编码的文本文件,需要给open()函数传入encoding参数,例如,读取GBK编码的文件:

with open(r'F:\jupyter notebook files\gbk.txt', 'r', encoding='gbk') as f:
a=f.read()
print(a)

输出如下:

gbk文本

遇到有些编码不规范的文件,你可能会遇到UnicodeDecodeError,因为在文本文件中可能夹杂了一些非法编码的字符。遇到这种情况,open()函数还接收一个errors参数,表示如果遇到编码错误后如何处理。最简单的方式是直接忽略

with open(r'F:\jupyter notebook files\gbk.txt', 'r', encoding='gbk',errors='ignore') as f: #注意errors='ignore'
a=f.read()
print(a)

2.2 读写方式列表

Python读写文件之with open()_文件读写

2.3 file object的属性

Python读写文件之with open()_python_02


参考文献:
​python 使用 with open() as 读写文件​​