FileNotFoundError: [Errno 2] No such file or directory: 'classA' in python, although the file has already been made
FileNotFoundError: [Errno 2] No such file or directory: 'classA' in python, although the file has already been made
sav = []
def fileKeep(sav):
classA = open("classA", "r")
for line in classA:
sav.append(line.split())
file.close()
return
fileKeep(sav)
我的代码到此结束。我收到一个文件未找到的错误,我在其他任何地方都没有得到,即使我也在接近代码开头的地方使用了该文件。欢迎任何帮助,谢谢。
您的代码假设当前工作目录与您的脚本所在的目录相同。这不是您可以做出的假设。
为您的数据文件使用绝对路径。您可以将其基于脚本的绝对路径:
import os.path
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
class_a_path = os.path.join(BASE_DIR, "classA")
classA = open(class_a_path)
如果您想知道您尝试打开数据文件的位置,您可以使用 os.getcwd()
验证当前工作目录。
您的函数可以简化为:
def fileKeep(sav):
with open(class_a_path) as class_:
sav.extend(l.split() for l in class_)
前提是 class_a_path
是全局的。
sav = []
def fileKeep(sav):
classA = open("classA", "r")
for line in classA:
sav.append(line.split())
file.close()
return
fileKeep(sav)
我的代码到此结束。我收到一个文件未找到的错误,我在其他任何地方都没有得到,即使我也在接近代码开头的地方使用了该文件。欢迎任何帮助,谢谢。
您的代码假设当前工作目录与您的脚本所在的目录相同。这不是您可以做出的假设。
为您的数据文件使用绝对路径。您可以将其基于脚本的绝对路径:
import os.path
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
class_a_path = os.path.join(BASE_DIR, "classA")
classA = open(class_a_path)
如果您想知道您尝试打开数据文件的位置,您可以使用 os.getcwd()
验证当前工作目录。
您的函数可以简化为:
def fileKeep(sav):
with open(class_a_path) as class_:
sav.extend(l.split() for l in class_)
前提是 class_a_path
是全局的。