Home > database >  How to read/write to many text files
How to read/write to many text files

Time:02-25

So in short, i have a directory that looks like

enter image description here

All the given text files look like

enter image description here

and I want to iterate through each file and input the text This is file #i at a certain line where i is the EXACT number of the file in its file name. I've watched countless videos on the os module, but still cant figure it out.

So just for reference,

enter image description here

is the goal im trying to reach for each file within the directory.

CodePudding user response:

I would do it like this:

indirpath = 'path/to/indir/'
outdirpath = 'path/to/outdir/'
files = os.listdir(indirpath)
inp_pos = 2 # 0 indexed line number where you want to insert your text

for file in files:
    name = os.path.splitext(file)[0]     # get file name by removing extension
    inp_line = f'This is file #{name}'    # this is the line you have to input
    lines = open(os.path.join(indirpath, file)).read().strip().split('\n')
    lines.insert(min(inp_pos, len(lines)), inp_line) # insert inp_line at required position

    with open(os.path.join(outdirpath, file), 'w') as outfile:
        outfile.write('\n'.join(lines))

You can have indirpath and outdirpath as the same if your goal is to overwrite the original files.

CodePudding user response:

You can use a simple approach of reading the lines, modifying them and writing back. This is good enough if your files are not very large. An eg.

def process_file(file, insert_index):
    file_lines = []
    # read the lines in file
    with open(file, "r") as f:
        file_lines = f.readlines()

    # insert the new line and write back to file
    with open(file, "w") as f:
        file_lines.insert(insert_index, f"This is file #{file.stem}\n")
        f.writelines(file_lines)


if __name__ == '__main__':
    from glob import glob
    import pathlib

    files = glob('./test/*.txt')  # list your files in the folder
    [process_file(pathlib.Path(file), 2) for file in files]  # Update each file in the list

CodePudding user response:

import os
folder_path = "you_folder"
row_you_expected_to_insert = 2

for file_name in os.listdir(folder_path):
    front_part = ""
    after_part = ""
    with open(os.path.join(folder_path, file_name), "r ") as f:
        for i in range(1,row_you_expected_to_insert):
            # read until the place you want to insert
            front_part  = f.readline()
        after_part = f.readlines()
        f.seek(0)
        f.write(front_part)
        f.write(f"This is file #{file_name.split('.')[-2]}\n")
        f.write("".join(after_part))
  • Related