Appending lines for existing file in python
This question already has an answer here:
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.
On the print_lines.py:
1 - You are looping forever, while True
, you need to add a breaking condition to exit the while loop or remove the while loop as you have the for loop.
2 - Argument 2 of curr_file = open('myfile',r)
must be string: curr_file = open('myfile','r')
3 - Close the file at the end: curr_file.close()
Now in add_lines:
1 - Open the file for appending not for writing over it, if you want to add lines: curr_file = open('myfile','a')
2 - Same as with previous file, Argument 2 of myfile = open('myfile',w)
must be string: curr_file = open('myfile','a')
上一篇: 在计划任务Python中写入文件
下一篇: 在python中追加现有文件的行