-3

I am newbie to python coding and need your expertise help in my below issue, Currently I am trying to read data from a txt file and process further once its moved to a list.

Below is my code:


case 'add':
            todo = input("enter a todo")+"\n"
            file = open('data.txt','r')
            todos =file.readlines()
            file.close()
            todos.append(todo)
            file = open('data.txt','w')
            file.writelines(todos)
            file.close()

Error I'm getting (please note both my main.py and data.txt are in the same folder)

 file = open('data.txt','r')
           ^^^^^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'data.txt'
  • "please note both my main.py and data.txt are in the same folder" - please see the linked duplicate, in order to understand why this is *not the important part*. A different rule is used to locate the file. – Karl Knechtel Jul 19 '23 at 07:39
  • 1
    Concerning the duplicate: I would advise against using `os.chdir`. The method with `pathlib` is much more flexible and less error-prone. – Matthias Jul 19 '23 at 07:40

1 Answers1

-1

You should include the full path to where data.txt is located if it's not in the same folder;
Example

open("D:\Text\data.txt","w+")
moken
  • 3,227
  • 8
  • 13
  • 23