![](/img/trans.png)
[英]Readlines method in Python skipping the first line in a file after heading
[英]Why is the Python .readlines() method seemingly erasing a file?
我试图创建一个待办事项列表应用程序,并存储用户任务,因此将它们逐行写到纯文本文件中。 在多个点上,我通过调用foo.readlines()
“同步”它,但是即使我将测试数据手动写入文件中,列表也将返回空,并且纯文本文件的内容将被擦除。
我尝试手动打开文件并将其写入并保存,但是运行脚本后,它再次为空,列表返回为空。
import numpy as np
file = open('./data.txt', 'w+')
tasks = file.readlines()
print(tasks)
#writes list to a file
def writeFile(tasks):
with open('data.txt', 'w') as filehandle:
for listitem in tasks:
filehandle.write('%s\n' % listitem)
您正在以write
模式打开文件,第3行带有“ w +”。这将删除文件的内容。
您可能打算在其中使用“ r”而不是“ w”
with open('data.txt', 'w') as filehandle:
如果未指定,则“读取”模式是默认模式
file = open('data.txt')
以“读取”模式打开文件
file = open('data.txt', 'r')
以“写入”模式打开文件(如果存在将覆盖文件内容)
file = open('data.txt', 'w')
以“追加”模式打开文件(将追加到现有文件中而不会被覆盖)
file = open('data.txt', 'a')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.