The script below does the job recursively.
Using exactly your example text:
dr = sys.argv
the list below contains the lines, to be added at the top. The lines will
appear in separate lines. In case you want to add an extra line break, use
\n like in the last two lines in the example- content below.
"abcdgd "+file.replace(".txt", "")+" dhsgabc",
"\negfbt hethtn nhnh",
for root, dirs, files in os.walk(dr):
for file in files:
path = root+"/"+file
# first read the file and edit its content
with open(path) as new:
text = ("\n").join(addlines(file))+"\n"+new.read()
# then write the edited text to the file
with open(path, "wt") as out:
It changes a file, called:
Liesje leerde Lotje lopen.txt
abcdgd Liesje leerde Lotje lopen dhsgabc
egfbt hethtn nhnh
How to use
- Copy the script into an empty file, save it as
- Change in the function
addlines(file) the text (but don't touch
\n stands for a(n extra) line break.
Run it with the targeted directory as an argument (the directory with your files):
python3 /path/to/change_file /directory
/directory includes spaces, use quotes:
python3 /path/to/change_file '/directory'
If the files are really huge, we might need to optimize the procedure a bit into a per line approach, but in average situations, this should work fine.