-1

I want to add lines to an existing file in python. I wrote the following two files

print_lines.py

while True:
    curr_file = open('myfile',r)
    lines = curr_file.readlines()
    for line in lines:
        print lines

add_lines.py

curr_file = open('myfile',w)
curr_file.write('hello world')
curr_file.close()

but when I run first print_lines.py and then add_lines.py I don't get the new line I add. How can I solve it?

Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
Alan Watts
  • 11
  • 6

2 Answers2

1

The issue is in the code -

curr_file = open('myfile',w)
curr_file.write('hello world')
curr_file.close()

The second argument should be a string, which indicates the mode in which the file should be openned, you should use a which indicates append .

curr_file = open('myfile','a')
curr_file.write('hello world')
curr_file.close()

w mode indicates write , it would overwrite the existing file with the new content, it does not append to the end of the file.

Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
1

On the print_lines.py:

1 - You are looping forever, while True, you need to add a breaking condition to exit the while loop or remove the while loop as you have the for loop.

2 - Argument 2 of curr_file = open('myfile',r) must be string: curr_file = open('myfile','r')

3 - Close the file at the end: curr_file.close()

Now in add_lines:

1 - Open the file for appending not for writing over it, if you want to add lines: curr_file = open('myfile','a')

2 - Same as with previous file, Argument 2 of myfile = open('myfile',w) must be string: curr_file = open('myfile','a')

Iron Fist
  • 10,739
  • 2
  • 18
  • 34