filename = 'learning_python.txt'
print("--- Reading in the entire file:")
with open(filename) as f:
contents = f.read()
print(contents)
print("\n--- Looping over the lines:")
with open(filename) as f:
for line in f:
print(line.rstrip())
print("\n--- Storing the lines in a list:")
with open(filename) as f:
lines = f.readlines()
for line in lines:
print(line.rstrip())
本文展示了如何使用Python读取本地文件“learning_python.txt”的三种方法:一次性读取整个文件,遍历文件的每一行,以及将文件的每一行存储到列表中。这是一篇适合Python初学者了解文件操作的基础教程。
3万+

被折叠的 条评论
为什么被折叠?



