在Python中打印多个文件的特定行

Ant*_*ure 3 python enumerate readlines python-3.x

我有30个文本文件,每个30行.出于某种原因,我需要编写一个打开文件1的脚本,打印文件1的第1行,关闭它,打开文件2,打印文件2的第2行,关闭它,依此类推.我试过这个:

import glob

files = glob.glob('/Users/path/to/*/files.txt')             
for file in files:
    i = 0
    while i < 30:
        with open(file,'r') as f:
            for index, line in enumerate(f):
                if index == i:
                    print(line)
                    i += 1
                    f.close()
            continue 
Run Code Online (Sandbox Code Playgroud)

显然,我收到以下错误:

ValueError:关闭文件的I/O操作.

因为f.close()的事情.如何只读取所需的行后,如何从文件移动到下一个文件?

Sha*_*ger 6

首先,回答问题,如评论中所述,您的主要问题是您关闭文件然后尝试继续迭代它.有罪的代码:

        for index, line in enumerate(f): # <-- Reads
            if index == i:
                print(line)
                i += 1
                f.close()                # <-- Closes when you get a hit
                                         # But loop is not terminated, so you'll loop again
Run Code Online (Sandbox Code Playgroud)

最简单的解决方法是,break而不是显式关闭,因为您的with语句已经保证在退出块时确定性关闭:

        for index, line in enumerate(f):
            if index == i:
                print(line)
                i += 1
                break
Run Code Online (Sandbox Code Playgroud)

但是因为这很有趣,所以这里有一个显着清理的代码来完成相同的任务:

import glob
from itertools import islice

# May as well use iglob since we'll stop processing at 30 files anyway    
files = glob.iglob('/Users/path/to/*/files.txt')

# Stop after no more than 30 files, use enumerate to track file num
for i, file in enumerate(islice(files, 30)):
    with open(file,'r') as f:
        # Skip the first i lines of the file, then print the next line
        print(next(islice(f, i, None)))
Run Code Online (Sandbox Code Playgroud)