Reputation: 155
I am trying to append a string ("testing123"
) to each line of every file in my current working directory (cache/configs
). This is what I've done:
import os
for file in os.listdir('cache/configs'):
with open('cache/configs/'+file, "r") as f:
lines = f.readlines()
for line in lines:
line = line+"testing123"
The command goes through without error, but nothing is changing. At face value my logic seems cogent. Where am I going wrong? Thanks.
[Python version 3.6]
Upvotes: 0
Views: 57
Reputation: 724
How about this?
import os
for file in os.listdir('cache/configs'):
cmd = "sed -i -e 's/$/ testing123/' cache/configs/{}".format(file)
os.system(cmd)
Upvotes: 0
Reputation: 5632
You're never saving the change.
import os
for file in os.listdir('cache/configs'):
with open('cache/configs/'+file, "r+") as f:
lines = f.readlines()
for i, line in enumerate(lines):
lines[i] = line.rstrip()+"testing123"
f.writelines(lines)
Upvotes: 3