【问题标题】:Python: [Errno 2] No such file or directory, whilst it IS in the directoryPython:[Errno 2]没有这样的文件或目录,虽然它在目录中
【发布时间】:2021-09-01 11:27:10
【问题描述】:

我有以下代码:

file_name = os.listdir("/Users/sophieramaekers/Downloads/CSV files") 

#remove the .csv part
file_name_noext = [f.replace('.csv', '') for f in file_name]
n_subjects = np.arange(0,len(file_name_noext))

#set path    
path = r'/Users/sophieramaekers/Downloads/CSV files'              
all_files = glob.glob(os.path.join(path, "*.csv")) 

#read all files
df_from_each_file=[]
for f in n_subjects:
    df_sub = pd.read_csv(file_name[f])
    df_from_each_file.append(df_sub) #append each df_sub to the df_from_each_file list                         

但我不断收到文件不在目录中的错误消息,而我 100% 确定它们在下载/CSV 文件目录中。谁能帮帮我?

我也试过这样:

df_from_each_file = [pd.read_csv(f) for f in all_files] #read all files

但是它只读取前两个文件,并在 n_subjects 的剩余长度内重复这两个文件。 (例如,假设文件名称为 aab abc abcd abcde,则 df_from_each_file 列表如下所示:[a ab aab a] 而不是 [a ab abc abcd abcde]

【问题讨论】:

    标签: python list csv for-loop


    【解决方案1】:

    file_name 是没有完整路径的文件名列表 (duh),因此它会在(我假设)不是 "/Users/sophieramaekers/Downloads/CSV files" 的工作目录中查找它们。

    所以尝试一下:

    df_from_each_file=[]
    for f in n_subjects:
        df_sub = pd.read_csv(os.path.join(path, file_name[f])) # adding the full path to the file
        df_from_each_file.append(df_sub) 
    

    【讨论】:

    • 抱歉再次打扰,但我注意到它现在只读取 de 'CSV files' 映射中的前两个文件,然后在循环的其余部分重复它(所以 df_from_each_file 由重复只有地图中的前两个文件)你知道这里出了什么问题吗?
    猜你喜欢
    • 2015-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-13
    • 1970-01-01
    相关资源
    最近更新 更多