用于文件中的Python?

tkb*_*kbx 1 python string loops file

有没有办法在Python中创建一个循环读取文件的循环,并使用该行执行操作?例如:

for eachLine in '~/file':
    print eachLine
Run Code Online (Sandbox Code Playgroud)

哪个会打印~/file到终端

Mar*_*ers 7

你是如此接近,你所要做的就是open()文件:

with open(os.path.expanduser('~/file')) as inputfile:
    for eachLine in inputfile:
        print eachLine
Run Code Online (Sandbox Code Playgroud)

通过使用with上下文管理器块,完成循环后文件将自动关闭.

  • 另外:OP可能需要使用`os.path.expanduser('〜/ file')`. (2认同)