Sunday, 6 January 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)
php - file_get_contents shows unexpected output while reading a file
I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...
-
I would like to split a String by comma ',' and remove whitespace from the beginning and end of each split. For example, if I have ...
-
I got an error in my Java program. I think this happens because of the constructor is not intialized properly. My Base class Program public ...
-
I have an app which needs a login and a registration with SQLite. I have the database and a user can login and register. But i would like th...
No comments:
Post a Comment