简体   繁体   中英

Python can't open file in same dir

I've met the strange behavior of my python after windows re-installation. python cant find and open text file in the same directory as running script! why?. I'm using python for many years and never had something like that. Now my old scripts which were worked fine before with file open not working at all. I dont want to fix them al. I want to know what is the issue. I have all of the python paths in my environment variables. So the code is just simple and I try to run script from C:\\untitled and txt file is also there.

import os.path
f = open('mytext.txt')
print(f)

So I'm receiving the following output:

Traceback (most recent call last):
  File "c:\untitled\helloworld.py", line 2, in <module>
    f = open('mytext.txt')
FileNotFoundError: [Errno 2] No such file or directory: 'mytext.txt'

So what can be the problem? How to fix it? Ive never met the issue like this.

The code you wrote opens the file in read mode by default. But we haven't specified how to print to python, try to print the file as below.

import os

f = open('myfile.txt', "r") #open('myfile.txt')
print(f.readline())

Cheers

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