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...
-
When the left part is an object instance, you use -> . Otherwise, you use :: . This means that -> is mostly used to access instance m...
-
I've been asked to update some Excel 2003 macros, but the VBA projects are password protected, and it seems there's a lack of docume...
-
I got a stupid problem with SQL that I can't fix. ALTER TABLE `news` ADD `dateAdded` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP AUTO...
No comments:
Post a Comment