python - 在python中将Excel文件与熊猫合并
问题描述
我几乎完成了将 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')
推荐阅读
- php - 我应该在 Yii 1.1 中使用什么方法在 MySQL 中求和?
- android - 如何强制 Kotlin 序列对 Kotlin 序列进行评估
- javascript - [Nodejs]如何在环回3中使用带有rest连接器的过滤器?
- python - 函数定义的 Pythonic 顺序是什么?
- android - NotificationCompat.PRIORITY_DEFAULT 在较旧的操作系统版本上没有声音
- android - 如何使用从服务中检索到的纬度和经度并在地图上显示它们?
- javascript - 将数组变量分配为收件人时,MailApp.sendEmail 返回奇怪的错误
- python - 如何在 Tkinter 中为事件启动动画循环?
- swift - 通过 AVAudioRecorder 在 WatchOS 上录制音频
- unity3d - 将按钮和照片作为游戏统一安装到屏幕上