[英]Why would Python think a file doesn't exist when I think it does?
I'm trying to import some files to plot, and all was going well until I moved my program to the directory above where it was before. 我正在尝试导入一些文件以进行打印,直到我将程序移至之前的目录之前,一切都进行得很好。 The relevant piece of code that seems to be problematic is below:
似乎有问题的相关代码如下:
import os
import pandas as pd
path = os.getcwd() + '/spectrum_scan/'
files = os.listdir(path)
dframefiles = pd.DataFrame(files)
up = pd.read_csv(dframefiles.ix[i][0])
If I type directly into the shell os.path.exists(path)
it returns True
. 如果我直接在外壳
os.path.exists(path)
键入,它将返回True
。
The first file in the directory spectrum_scan
is foo.csv
. 目录
spectrum_scan
的第一个文件是foo.csv
。
When I type os.path.exists(path + 'foo.csv')
it returns True
but os.path.isfile('foo.csv')
returns False
. 当我输入
os.path.exists(path + 'foo.csv')
它返回True
但是os.path.isfile('foo.csv')
返回False
。
Also, asking for files
and dframefiles
returns everything as it should, but when the code is run I get Exception: File foo.csv does not exist
. 另外,询问
files
和dframefiles
返回所有内容,但是在运行代码时出现Exception: File foo.csv does not exist
。
Is there something obvious I'm missing? 有什么明显的我想念的东西吗?
You are using os.listdir()
, which returns filenames without a path. 您正在使用
os.listdir()
,该os.listdir()
返回不带路径的文件名。 You'll need to add the path to these: 您需要为这些添加路径:
files = [os.path.join(path, f) for f in os.listdir(path)]
otherwise python will try and look for 'foo.csv'
in the current directory, and not in the spectrum_scan
sub-directory where the files really are located. 否则,python将尝试在当前目录中查找
'foo.csv'
,而不是在文件实际所在的spectrum_scan
子目录中查找。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.