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 am new to dask and I found so nice to have a module that makes it easy to get parallelization. I am working on a project where I was able ...
-
Award winning movie director, producer, and writer, who is best known for movies Blue Velvet, Dune, and Mulholla...
No comments:
Post a Comment