open all the text files in a folder

Viewed 35

i have this code that takes in a text folder and takes the 25th element in the first line of the file and place it in the 7th. However, this code opens only one text file and writes it to another but what i want that the code reads all the files in the folder and writes them in the same path.

index= 1
with open("3230c237cnc274c.txt", "r") as f:
    file = f.readlines()

line = file[index].split(';')
target = line[24]
blank = line[6]
line[6] = target
line[24] = ""
file[index] = ';'.join(line)

with open("aaaaaaaaaaaaaaaa.txt", 'w') as f:
    for line in file:
        f.write(line)
1 Answers

I like to use the glob module for things like this. See if this helps:

import glob

all_text_files = glob.glob("*.txt")
for text_file in all_text_files:
    with open(text_file, "r") as f:
        lines = f.readlines()
        # do something with the lines...

The syntax "*.txt" indicates all files ending with the .txt extension. This then returns a list of all those filenames. If your files are in a folder somewhere, you can also do "folder/*.txt", and there's a few other nice tricks with glob

Related