我正在尝试遍历Python目录,并且我有一个特定文件恰好是目录中的最后一个文件,因此我得到该特定文件的IOerror
。
我得到的错误是:
IOError: [Errno 2] No such file or directory: 'nod_gyro_instance_11_P_4.csv'
我的剧本:
for filename in os.listdir("/Users/my_name/PycharmProjects/My_Project/Data/Nod/Gyro"):
data = []
if filename.endswith(".csv"):
data.append(k_fold(filename))
continue
else:
continue
k_fold这样做:
def k_fold(myfile, myseed=11109, k=20):
# Load data
data = open(myfile).readlines()
整个追溯:
Traceback (most recent call last):
File "/Users/my_name/PycharmProjects/MY_Project/Cross_validation.py", line 30, in <module>
data.append(k_fold(filename))
File "/Users/my_name/PycharmProjects/My_Project/Cross_validation.py", line 8, in k_fold
data = open(myfile).readlines()
IOError: [Errno 2] No such file or directory: 'nod_gyro_instance_11_P_4.csv'
我的CSV文件是这样的:
nod_gyro_instance_0_P_4.csv
nod_gyro_instance_0_P_3.csv
nod_gyro_instance_0_P_2.csv
nod_gyro_instance_0_P_5.csv
...
nod_gyro_instance_11_P_4.csv
nod_gyro_instance_10_P_6.csv
nod_gyro_instance_10_P_5.csv
nod_gyro_instance_10_P_4.csv
为什么不识别我的nod_gyro_instance_10_P_4.csv
文件?
答案 0 :(得分:3)
os.listdir
只返回文件名,而不是绝对路径。如果您当前不在同一目录中,则尝试读取该文件将失败。
您需要将dirname加入到返回的文件名中:
data_dir = "/Users/my_name/PycharmProjects/My_Project/Data/Nod/Gyro"
for filename in os.listdir(data_dir):
k_fold(os.path.join(data_dir, filename))
或者,您可以使用glob
同时执行列表(包含完整路径)和扩展名过滤:
import glob
for filename in glob.glob("/Users/my_name/PycharmProjects/My_Project/Data/Nod/Gyro/*.csv"):
k_fold(filename)