有没有办法在 Python 中创建一个循环,逐行读取文件,并使用该行执行操作?例如:
for eachLine in '~/file':
print eachLine
这会将 ~/file 打印到终端
请您参考如下方法:
你是如此接近,你所要做的就是open()文件:
with open(os.path.expanduser('~/file')) as inputfile:
for eachLine in inputfile:
print eachLine
通过使用 with 上下文管理器 block ,当您完成循环时文件会自动关闭。
