简体   繁体   English

为什么Python .readlines()方法似乎删除了文件?

[英]Why is the Python .readlines() method seemingly erasing a file?

I am trying to create a to-do list application, and to store the users tasks, I'm writing them by line to a plaintext file. 我试图创建一个待办事项列表应用程序,并存储用户任务,因此将它们逐行写到纯文本文件中。 At multiple points I "sync" it by calling foo.readlines() , but even if I hand write test data into the file, the list returns empty and the contents of the plain text file are erased. 在多个点上,我通过调用foo.readlines() “同步”它,但是即使我将测试数据手动写入文件中,列表也将返回空,并且纯文本文件的内容将被擦除。

I tried opening the file manually and writing to it and saving it, but after running the script, it is again empty and the list returns empty. 我尝试手动打开文件并将其写入并保存,但是运行脚本后,它再次为空,列表返回为空。

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)

You're opening the file in write mode with "w+" at line 3. That deletes the file's contents. 您正在以write模式打开文件,第3行带有“ w +”。这将删除文件的内容。

You probably meant to use "r" instead of "w" in 您可能打算在其中使用“ r”而不是“ w”

with open('data.txt', 'w') as filehandle:

'Read' mode is the default mode if none specified 如果未指定,则“读取”模式是默认模式

file = open('data.txt')

Opening a file in 'Read' mode 以“读取”模式打开文件

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

Opening a file in 'Write' mode (will overwrite the contents of the file if exists) 以“写入”模式打开文件(如果存在将覆盖文件内容)

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

Opening a file in 'Append' mode (will append to the existing file without overwriting) 以“追加”模式打开文件(将追加到现有文件中而不会被覆盖)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM