簡體   English   中英

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

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM