pythonpython-3.xtext-fileswritefilewritetofile

How to read/write to many text files


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.


Solution

  • 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.