简体   繁体   中英

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.

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.

You probably meant to use "r" instead of "w" in

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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