gpt4 book ai didi

python - 在python中将Excel文件与 Pandas 合并

转载 作者:行者123 更新时间:2023-12-04 21:28:31 25 4
gpt4 key购买 nike

我几乎完成了将 excel 文件与 python 中的 pandas 合并,但是当我给出路径时它不会工作。我收到错误“没有这样的文件或目录:'file1.xlsx''”。当我将路径留空时,它可以工作,但我想决定它应该从哪个文件夹中获取文件。我将文件保存在文件夹“excel”中

cwd = os.path.abspath('/Users/Viktor/downloads/excel') #If i leave it empty and have files in /Viktor it works but I have the desired excel files in /excel 

print(cwd)
files = os.listdir(cwd)
df = pd.DataFrame()
for file in files:
if file.endswith('.xlsx'):
df = df.append(pd.read_excel(file), ignore_index=True)
df.head()
df.to_excel(r'/Users/Viktor/Downloads/excel/resultat/merged.xlsx')

最佳答案

pd.read_excel(file) 查找相对于脚本执行路径的文件。如果您在“/Users/Viktor/”中执行,请尝试:

import os
import pandas as pd

cwd = os.path.abspath('/Users/Viktor/downloads/excel') #If i leave it empty and have files in /Viktor it works but I have the desired excel files in /excel

#print(cwd)
files = os.listdir(cwd)


df = pd.DataFrame()
for file in files:
if file.endswith('.xlsx'):
df = df.append(pd.read_excel('downloads/excel/' + file), ignore_index=True)
df.head()
df.to_excel(r'/Users/Viktor/downloads/excel/resultat/merged.xlsx')

关于python - 在python中将Excel文件与 Pandas 合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63041257/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com