So in short, i have a directory that looks like
All the given text files look like
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,
is the goal im trying to reach for each file within the directory.
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.