Daniel Hutchinson
Daniel Hutchinson

Reputation: 165

Python: editing a series of txt files via loop

With Python I'm attempting to edit a series of text files to insert a series of strings. I can do so successfully with a single txt file. Here's my working code that appends messages before and after the main body within the txt file:

filenames = ['text_0.txt']

with open("text_0.txt", "w") as outfile:
    for filename in filenames:
        with open(filename) as infile:
            header1 = "Message 1:"
            lines = "\n\n\n\n"
            header2 = "Message 2:"
            contents = header1 + infile.read() + lines + header2
            outfile.write(contents)

I'm seeking some assistance in structuring a script to iteratively make the same edits to a series of similar txt files in the directory. There are 20 or similar txt files are structured the same: text_0.txt, text_1.txt, text_2.txt, and so on. Any assistance is greatly appreciated.

Upvotes: 0

Views: 149

Answers (2)

Abhi
Abhi

Reputation: 1005

If you already know the file naming then you can simply loop:

filenames = [f'text_{index}.txt' for index in range(21)]

for file_name in filenames:
    with open(file_name, "w") as outfile:
    for filename in filenames:
        with open(filename) as infile:
            header1 = "Message 1:"
            lines = "\n\n\n\n"
            header2 = "Message 2:"
            contents = header1 + infile.read() + lines + header2
            outfile.write(contents)

Or loop the directory like:

import os

for filename in os.listdir(directory):
      #do something , like check the filename in list

Upvotes: 1

Mhmd Admn
Mhmd Admn

Reputation: 369

to loop through a folder of text files, you need to do it like this:

import os


YOURDIRECTORY = "TextFilesAreHere" ##this is the folder where there's your text files

for file in os.listdir(YOURDIRECTORY):
    filename = os.fsdecode(file)
    with open(YOURDIRECTORY  + "/" + filename, "r"):
        ###do what you want with the file

Upvotes: 1

Related Questions