Reputation: 13
I know something similar has been asked before but I'm new to python and I can not find a solution for my problem:
What I want to do is this: 1. Open a file and read it line by line. (I already managed to do that) 2. Add something new after each line. (I want to combine this with an if statement later so that only specific lines will get edited)
My code:
#!/usr/bin/python3.4
file = open('testfile', 'r+')
readlinebyline = file.readline()
for i in range(0, len(readlinebyline)):
readlinebyline.write(' ' + 'checked')
print('done')
I want my testfile to look like this afterwards:
line1 checked
line2 checked
line3 checked
...
But instead it looks like this:
line1
line2
line3
checked checked checked
How do I get the program to stop after each line and then add something new to it?
Upvotes: 1
Views: 504
Reputation: 598
with open('file.txt', 'r') as f:
content = f.readlines()
with open('file.txt', 'w') as f:
for line in content:
f.write(line.strip('\n') + ' checked\n')
Upvotes: 0
Reputation: 13
testfile=open('uat_config.conf', 'r+')
readlinebyline=testfile.readlines()
for i in range(0, len(readlinebyline)):
testfile.write("CHECKED "+ str(readlinebyline[i]))
print('done')
Upvotes: 0
Reputation: 4441
You can make use of readlines
with open('testfile', 'r') as file:
# read a list of lines into data
lines = file.readlines()
with open('testfile', 'w') as file:
for line in lines:
# do your checks on the line..
file.write(line.strip() + ' checked' )
print('done')
Upvotes: 1
Reputation: 1755
I'd recommend going line by line writing the file to a new file and then moving that new file to the original file which will overwrite it:
import shutil
filename = '2017-11-02.txt'
temp_filename = 'new.txt'
with open(filename, 'r') as old, open(temp_filename, 'w') as new:
# Go line by line in the old file
for line in old:
# Write to the new file
new.write('%s %s\n' % (line.strip(),'checked'))
shutil.move(temp_filename, filename)
Somewhat related answer that I based this off of: https://stackoverflow.com/a/16604958/5971137
Upvotes: 0