文件IO¶
通常情况下,你的计划的结果不仅在现在很重要,而且在将来也很重要。为此,最好将结果存储在文件中,以便以后在必要时使用它们。这称为文件输入和输出,简称为:文件IO。
从文件读取¶
在python中打开文件的最佳方法是使用 the with statement .这将自动打开文件,并对其保持锁定,以便在您使用该文件时没有人能够修改它,然后将其关闭。然后,通过使用在后面指定的变量来与文件进行交互。 as
.这叫A file object .要获取文件的完整内容,请使用 read()
方法如下:
>>> with open('csv_file.txt', 'r') as f:
... file_content = f.read()
...
>>> print(file_content)
1, 2, 3
4, 5, 6
7, 8, 9
其中第一个参数是文件的路径,第二个参数是所谓的文件模式。 r
是只读的。
注解
在一些教程和生产代码中,您可能会发现一些与文件交互的东西:
>>> f = open('csv_file.txt', 'r')
>>> file_content = f.read()
>>> f.close()
>>> print(file_content)
1, 2, 3
4, 5, 6
7, 8, 9
这是以前处理文件的方式 the with statement 还不存在。它有一个巨大的缺点,那就是你必须注意关闭文件。如果在 open
和 close
它一点也不关。 The with statement 即使是在例外的情况下,也要为您处理这个问题,这是随后的首选方式。
您还可以迭代 f
就像是某种容器:
>>> with open('csv_file.txt', 'r') as f:
... for i, line in enumerate(f):
... print('Line', i, '--', line)
...
Line 0 -- 1, 2, 3
Line 1 -- 4, 5, 6
Line 2 -- 7, 8, 9
如你所见,你会得到一些额外的白线。原因是每一行仍然包含其换行符 \n
最后。到这一个 print()
默认情况下,添加一个额外的,这样您最终会得到一个空行。为了避免这种情况,使用 strip()
字符串的方法:
>>> with open('csv_file.txt', 'r') as f:
... for i, line in enumerate(f):
... stripped_line = line.strip()
... print('Line', i, '--', stripped_line)
...
Line 0 -- 1, 2, 3
Line 1 -- 4, 5, 6
Line 2 -- 7, 8, 9
正在写入文件¶
要写入文件,必须先打开它,这次使用 w
作为文件打开模式,指示您要写入文件。然后你可以使用 write()
要写入文件的文件对象的方法:
>>> with open('my_first_file.txt', 'w') as f:
... f.write('This is smart.')
... f.write('This is even smarter.')
...
14
21
现在你的文件的内容是
This is smart.This is even smarter.
格式不好。所以你必须注意添加换行符 \n
以及相应的空间:
>>> with open('my_first_file.txt', 'w') as f:
... f.write('This is smart.\n')
... f.write('This is even smarter.\n')
...
15
22
随后,文件的内容将是
This is smart.
This is even smarter.
总结¶
您可以使用
open()
A中的函数with
语句。只从文件中读取,用文件模式打开文件
r
并使用read()
文件对象的方法。要从文件写入,请使用文件模式打开它
w
并使用write
文件对象的方法。