如何将Python代码创建的Excel表保存到我创建的桌面文件夹?

0 投票
1 回答
44 浏览
提问于 2025-04-13 16:06

我一直在努力把我从数据框创建的Excel表格保存到一个自动生成的文件夹里,这个文件夹是在桌面上。现在,Excel表格被保存在IDE的目录里,但我想把它移动到桌面文件夹,或者至少复制过去:

import os 
import shutil
import pandas as pd 

#The data frame has been created previously 

excel_name= 'abc.xlsx'
data_frame.to_excel(excel_name,index= True)


#saving the documents in a desktop file

#Define the path to the folder where you want to move/copy the files 

folder_path = os.path.join(os.path.expanduser("~"), "Desktop", "Excel Files Folder")

#Create the folder if it doesn't exist
if not os.path.exists(folder_path):
   os.makedirs(folder_path)
     
os.path.join(folder_path, excel_name)
shutil.copy(excel_name, folder_path)


但是在这样做的时候,我遇到了一个错误:

FileNotFoundError: [Errno 2] 没有这样的文件或目录: 'C:\Users\peha\Desktop\Excel Files Folder \abc.xlsx'

我也试过用shutil.move,但还是遇到同样的错误。谢谢你的帮助!

附言:我正在尝试把这个功能实现到我正在创建的小软件里,所以我希望它能在任何电脑上都能正常工作。

1 个回答

0

pandas.DataFrame.to_excel 这个函数需要你提供一个完整的文件路径,才能把数据保存到文件里。

所以,你首先得创建好文件夹,然后再用 pandas.DataFrame.to_excel 这个函数来保存文件,记得要把文件夹和文件名一起写上,也就是完整的路径:

folder_path = os.path.join(os.path.expanduser("~"), "Desktop", "Excel Files Folder")

if not os.path.exists(folder_path):
    os.makedirs(folder_path)

excel_name = "abc.xlsx"

data_frame.to_excel(os.path.join(folder_path, excel_name), index=True)

撰写回答