[英]Getting a error: FileNotFoundError: [Errno 2] No such file or directory: while trying to open a file
In a Folder called Assignment Parser, I've my parsing.py file along with a auth.txt file. 在名为Assignment Parser的文件夹中,我拥有parsing.py文件和auth.txt文件。 Trying to open this auth.txt file.
尝试打开此auth.txt文件。 But getting an error that says :
但是得到一个错误,说:
(base) C:\Users\Ajay\Desktop\Python\Assignment Parser>python parsing.py
Traceback (most recent call last):
File "parsing.py", line 27, in <module>
main()
File "parsing.py", line 8, in main
file = open(file_path / "auth.txt","r")
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Ajay\\Desktop\\Python\\Assignment Parser\\auth.txt'
Code: 码:
from pathlib import Path
import os
def main():
# read file
# C:\Users\Ajay\Desktop\Python\Assignment Parser\
file_path = Path("C:/Users/Ajay/Desktop/Python/Assignment Parser/")
file = open(file_path / "auth.txt","r")
# file = open("auth.txt", "r")
lines = file.readlines()
file.close()
Where is this going wrong? 哪里出问题了? PFA for the screenprint.
屏幕截图的PFA。
Try this: 尝试这个:
from pathlib import Path
import os
def main():
# read file
# C:\Users\Ajay\Desktop\Python\Assignment Parser\
file_path = Path("C:/Users/Ajay/Desktop/Python/Assignment Parser/")
file = open(os.path.join(file_path, "auth.txt"), "r")
# file = open("auth.txt", "r")
lines = file.readlines()
file.close()
I think the problem is in file extension, I see parsing
has .py extension but auth
is not 我认为问题出在文件扩展名中,我看到
parsing
具有.py扩展名,但auth
却没有
please try file = open(file_path / "auth", "r")
again (just delete .txt
extension) 请再次尝试使用
file = open(file_path / "auth", "r")
(只需删除.txt
扩展名)
As you have your python file in same folder as your text file. 因为您的python文件与文本文件位于同一文件夹中。 You can directly use below code.
您可以直接使用以下代码。
def main():
file = open("./auth.txt")
lines = file.readlines()
file.close()
Also make sure, your syder working directory is set to this folder path "C:/Users/Ajay/Desktop/Python/Assignment Parser" 还要确保将您的syder工作目录设置为此文件夹路径“ C:/ Users / Ajay / Desktop / Python / Assignment Parser”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.