Python 文件读取:一次读取全部内容和逐行读取
Python 文件读取:一次读取全部内容和逐行读取
在 Python 中,我们可以使用 open() 函数打开文件,并使用不同的方法读取文件内容。以下介绍两种常用的方法:
(1) 一次读取全部内容:
with open('test.txt', 'r') as file:
content = file.read()
print(content)
此方法将整个文件内容读入一个字符串变量 content 中。
示例文件 test.txt 的内容如下:
'Hello, world!'
'This is a test file.'
'Hope it works well.'
运行以上代码,将会输出以下结果:
'Hello, world!'
'This is a test file.'
'Hope it works well.'
(2) 每次读取一行:
with open('test.txt', 'r') as file:
for line in file:
print(line.strip())
此方法逐行读取文件内容,并使用循环打印每一行。line.strip() 用于去除每行末尾的换行符。
运行以上代码,将会输出以下结果:
'Hello, world!'
'This is a test file.'
'Hope it works well.'
选择哪种方法取决于您的需求。 如果您需要一次性处理整个文件内容,则使用第一种方法更方便;如果需要逐行处理文件内容,则使用第二种方法更合适。
原文地址: https://www.cveoy.top/t/topic/nXYm 著作权归作者所有。请勿转载和采集!