阅读时双斜杠
double slash when reading
使用这部分代码
for root, dirs, files in os.walk(data_location):
for file in files:
if file.endswith(".xlsx"):
df = pd.read_excel(data_location + "\" + file, usecols=col_list)
df['File']=file
df_total = pd.concat([df, df_total], ignore_index=True)
出现此错误:
FileNotFoundError: [Errno 2] No such file or directory: "C:\Users\bosuna\
如您所见,它在运行时将路径中的“”加倍。
您没有将正确的文件路径传递给 pd.read_excel()
。 data_location
只是您正在搜索的顶级文件夹,file
是文件名。 os.walk()
沿着文件夹结构向下移动,并通过您拥有的变量 root
传递它所在的每个文件夹。所以下面一行
df = pd.read_excel(data_location + "\" + file, usecols=col_list)
应该是:
df = pd.read_excel(root + "\" + file, usecols=col_list)
甚至更好:
df = pd.read_excel(os.path.join(root, file), usecols=col_list)
使用这部分代码
for root, dirs, files in os.walk(data_location):
for file in files:
if file.endswith(".xlsx"):
df = pd.read_excel(data_location + "\" + file, usecols=col_list)
df['File']=file
df_total = pd.concat([df, df_total], ignore_index=True)
出现此错误:
FileNotFoundError: [Errno 2] No such file or directory: "C:\Users\bosuna\
如您所见,它在运行时将路径中的“”加倍。
您没有将正确的文件路径传递给 pd.read_excel()
。 data_location
只是您正在搜索的顶级文件夹,file
是文件名。 os.walk()
沿着文件夹结构向下移动,并通过您拥有的变量 root
传递它所在的每个文件夹。所以下面一行
df = pd.read_excel(data_location + "\" + file, usecols=col_list)
应该是:
df = pd.read_excel(root + "\" + file, usecols=col_list)
甚至更好:
df = pd.read_excel(os.path.join(root, file), usecols=col_list)