Home > Back-end >  Loop for opening .txt files
Loop for opening .txt files

Time:01-20

I have a list of .txt file in one folder, with names like: "image1.txt", "image2.txt", "image3.txt", etc.

I need to perform some operations for each file.

I was trying like this:

import glob
for each_file in glob.glob("C:\...\image\d \.txt"):
print(each_file) (or whatever)

But it seems it doesn't work. How can I solve?

CodePudding user response:

I think you are looking for something like this:

import os

for file in os.listdir('parent_folder'):
    with open(os.path.join('parent_folder', file), 'r') as f:
        data = f.read()
        # operation on data

#Alternatively
for i in range(10):
    with open(f'image{i}.txt', 'r') as f:
        data = f.read()
        # operation on data

The with operator takes care of everything to do with the file, so you don't need to worry about the file after it goes out of scope.

If you want to read and also write to the file in the same operation, use open(file, 'r ) and then the following:

with open(f'image{i}.txt', 'r ') as f:
    data = f.read()
    # operation on data

    f.seek(0)
    f.write(data)
    f.truncate()

CodePudding user response:

Take this answer, that I wrote.

path objects have the read_text method. As long as it can decode it, then it will read it - you shouldn't have a problem with text files. Also, since you are using windows paths, make sure to put an r before the string, like this r"C:\...\image\d \.txt" or change the direction of the slashes. A quick example:

from pathlib import Path

for f in Path(r"C:\...\image\d \").rglob('**/*.txt'):
    print(f.read_text())
  • Related