首页 > 解决方案 > 为什么 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)

标签: pythonfilesave

解决方案


如果未指定,则“读取”模式是默认模式

file = open('data.txt')

以“读取”模式打开文件

file = open('data.txt', 'r')

以“写入”模式打开文件(如果存在,将覆盖文件的内容)

file = open('data.txt', 'w')

以“追加”模式打开文件(将追加到现有文件而不覆盖)

file = open('data.txt', 'a')

推荐阅读