Sunday, January 6, 2019

Appending lines for existing file in python

Answer


Answer





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?


Answer



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.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...