简体   繁体   中英

Python can open a file in w mode, but not i r

I have two files: abc.txt test.py

Both are in the folder C:\\test

test.py contains only one line, it tries to open the textfile:

f = open("abc.txt", "rt")

When I run test.py I get an error:

C:\Users\stefan>python.exe C:\test\test.py
Traceback (most recent call last):
  File "C:\test\test.py", line 1, in <module>
    f = open("abc.txt", "rt")
IOError: [Errno 2] No such file or directory: 'abc.txt'

Now I change from mode "rt" to "wt" => good no error anymore

I change back to mode "rt" => good, again no error

So why the file gets only found in mode "wt"? And why it works afterwards as well in "rt" mode again...?

I'm running Python 2.7.13 on Win10

You must either give the full, absolute path to open() or copy abc.txt into your current working directory, which seems to be C:\\Users\\stefan .

open(.., "wt") succeeds, because it can create a file if it does not exist.

Basically when you run the program as

C:\Users\stefan>python.exe C:\test\test.py

python tries to look for the file abc.txt in directory C:\\Users\\stefan> . Since the file is not there the program fails.

bc.txt test.py

Both are in the folder C:\test

For the program to work fine go to this directory C:\\test\\ and run the program as:

python.exe test.py

It will run fine.

Now why does it work the 2nd time

Now I change from mode "rt" to "wt" => good no error anymore

I change back to mode "rt" => good, again no error

When you change the mode from 'rt' to 'wt' the program creates a file abc.txt in the directory C:\\Users\\stefan> and thus when you change 'wt' back to 'rt' it starts working fine.

I re-created your error in my program like this : structure in my program

├── abc
│   ├── abc.txt
│   └── prog.py

Output looks like this:

➜  abc python prog.py #works fine
➜  abc cd ..
➜  /tmp python abc/prog.py
Traceback (most recent call last):
  File "abc/prog.py", line 1, in <module>
    f = open("abc.txt", "rt")
FileNotFoundError: [Errno 2] No such file or directory: 'abc.txt'

My program code looks like this:

➜  /tmp cat abc/prog.py
f = open("abc.txt", "rt")

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