1

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?

Uckel
  • 13
  • 3
  • You aren't reading line-by-line, you are reading the entire file at once, also, the code you provided would produce several errors. – juanpa.arrivillaga Nov 02 '17 at 16:56
  • The code is not producing any errors. Sorry I didn't use testfile.readlines(). I used testfile.readline(). If that makes a difference. Just edited that – Uckel Nov 02 '17 at 16:57
  • Yes. It would produce a `NameError` because `testfile` is not defined, even if it *were*, then `for i in range(0, len(readlinebyline()):` would throw a `TypeError` because list-objects are not callable. And even barring that, `readlinebyline.write` would throw an `AttributeError`, because list-objects don't have a `write` attribute. – juanpa.arrivillaga Nov 02 '17 at 16:59
  • But basically, if you can afford to read the entire file into memory, the easiest thing is to read it all in to memory (as a list as you have done), then truncate the file, then write it out as you would like. – juanpa.arrivillaga Nov 02 '17 at 17:03
  • You need to write the new content on a new file and then delete `testfile` and rename the new file `testfile`. – Daniele Bacarella Nov 02 '17 at 17:03
  • 1
    It's almost always better to make a new file with the modifications rather than trying to modify the file you're reading. And of course once the new file is closed you can easily replace the original file with it if you like. Not only is it simpler to work like that, it's safer: if your machine crashes or loses power while your code is running your data won't be mangled. – PM 2Ring Nov 02 '17 at 17:04

4 Answers4

1

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')
be_good_do_good
  • 4,311
  • 3
  • 28
  • 42
0

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

Cole
  • 1,715
  • 13
  • 23
0
testfile=open('uat_config.conf', 'r+')
readlinebyline=testfile.readlines()
for i in range(0, len(readlinebyline)):
 testfile.write("CHECKED "+ str(readlinebyline[i]))
print('done')
Divya
  • 13
  • 1
  • 4
0
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')
lpozo
  • 598
  • 2
  • 9
  • Simplest solution. – George Sovetov Nov 02 '17 at 18:05
  • Thank you, this is exactly what I needed. It works fine. But I don't fully understand the "line.strip('\n')" part yet. The strip method seems to remove specific characters from the line. So does it remove the empty space in every iteration in this case? Sorry, I'm still a noob. An answer would be highly appreciated. I really want to understand this – Uckel Nov 05 '17 at 11:00
  • No, it removes only the '\n', that is, new line character at the end of every line, so you can add ' checked\n' in the same line. – lpozo Nov 06 '17 at 13:42