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.
Subscribe to:
Post Comments (Atom)
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...
-
This question attempts to collect the few pearls among the dozens of bad C++ books that are published every year. Unlike many other programm...
-
I need to do the following: My current address looks like: https://www.domain.com I want to redirect with htaccess: www.domain.com TO https:...
-
using namespace std; So far in my computer science courses, this is all we have been told to do. Not only that, but it's all tha...
No comments:
Post a Comment