python - 为什么 Python .readlines() 方法似乎在擦除文件?
问题描述
我正在尝试创建一个待办事项列表应用程序,并存储用户任务,我将它们逐行写入纯文本文件。在多个点我通过调用“同步”它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)
解决方案
如果未指定,则“读取”模式是默认模式
file = open('data.txt')
以“读取”模式打开文件
file = open('data.txt', 'r')
以“写入”模式打开文件(如果存在,将覆盖文件的内容)
file = open('data.txt', 'w')
以“追加”模式打开文件(将追加到现有文件而不覆盖)
file = open('data.txt', 'a')
推荐阅读
- vba - 编辑超链接以从路径中删除文件名
- visual-studio-2015 - Visual Studio:使用外部物理设备(不是本地主机)测试 WebAPI
- linux - Nifi 容器 cpu 使用率高
- yum - yum 中的 apt-key 等价物是什么?
- r - 如何将R中的两个矩阵相乘?
- python - 尽管使用 GObject.idle_add,python3 gtk3 GUI 仅部分更新
- compression - 如何压缩唯一值为 1、0 和 -1 的时间序列
- dns - 如何在自定义 github 页面域上修复 ERR_TOO_MANY_REDIRECTS?
- swift - 单击按钮后如何写入文件
- django - 允许端口的问题 - docker/django