I have 30 text files of 30 lines each. For some reason, I need to write a script that opens file 1, prints line 1 of file 1, closes it, opens file 2, prints line 2 of file 2, closes it, and so on. I tried this:
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
Obviously, I got the following error:
ValueError: I/O operation on closed file.
Because of the f.close() thing. How can I do to move from a file to the next one after reading only the desired line?
breakto exit a loop; replacef.close()with that. Thecontinueat the bottom is also unnecessary, and the outer loop can be afor i in range(0, 30):(ori, file in enumerate(files)?) without explicitly incrementingi.f.close()isn't needed at all because you (correctly) used thewithstatement whenopening the file, ensuring that it is automatically closed when you exit the block.itertools.islice. Replace the whole contents of thewithblock withprint(next(itertools.islice(f, i, None))), no need for explicit looping of any kind. This requires @Ryan's suggested change of replacing the outerwhileloop with afor i, file in enumerate(files):(or to ensure you only process 30 files,for i, file in enumerate(islice(files, 30)):) so you're not manually tracking/incrementingi.