Python-读取一个文件的内容的方法

147 阅读1分钟

要读取一个文件的内容,首先你需要用open() 全局函数打开它,该函数接受2个参数:文件路径和模式

要读取,请使用读取 (r) 模式。

filename = '/Users/flavio/test.txt'

file = open(filename, 'r')

#or

file = open(filename, mode='r')

一旦你打开了文件,你可以使用read() 方法将文件的全部内容读成一个字符串。

你也可以选择逐行读取内容。

常见的做法是将其与一个循环结合起来,例如,将每一行都读成一个列表条目。

filename = '/Users/flavio/test.txt'

file = open(filename, 'r')

while True:
    line = file.readline()
    if line == '': break
    print(line)

在你的文件处理结束时,记得要关闭文件。