使用 os.walk 无法从列表中打开文件 [英] using os.walk cannot open the file from the list
问题描述
我的问题是读取目录中的.csv"文件并对其进行一些计算.我有计算工作,但我的 for 循环似乎没有按我想的那样工作.
My problem is to read '.csv' files in catalogs and do some calculations on them. I have calculations working but my for loop seem not to work as I want to.
d = 'F:\MArcin\Experiments\csvCollection\'
for dirname, dirs, files in os.walk(d):
for i in files:
if i.endswith('.csv'):
data1 = pd.read_csv(i, sep=",")
data = data1['x'][:, np.newaxis]
target = data1['y']
我得到的错误是:IOError: 文件 1.csv 不存在
The error Iam getting is: IOError: File 1.csv does not exist
files 是目录名中所有.csv"文件的列表
files is list of all '.csv' files inside dirname
i 是大小为 1 的 str 并包含 1.csv(即目录中的第一个文件)
i is str of size 1 and contains 1.csv (that is first of the files in catalog)
知道为什么这不起作用吗?
Any ideas why this is not working?
感谢您的帮助.
推荐答案
因为 1.csv
位于文件系统的某个位置,当您调用 read_csv()
时,它会打开文件相对于当前目录.
Because 1.csv
is somewhere on the filesystem and when you call read_csv()
it opens file relative to current directory.
使用绝对路径打开即可:
Just open it using absolute path:
data1 = pd.read_csv(os.path.join(dirname, i), sep=",")
os.walk
中的
dirname
代表文件1.csv
所在的实际目录.
dirname
in os.walk
represents actual directory where file 1.csv
is located.
这篇关于使用 os.walk 无法从列表中打开文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!