0

我通常将在 Python 脚本中创建的 xls 文件保存在我的硬盘上。例如,对于 pandas,这通常是一件非常直接的事情。

我的问题是我正在尝试从 py2app 编译的脚本中完成此操作。我尝试使用easygui询问将文件保存在哪里(哪个文件夹),但我不确定如何去做,一旦编译到应用程序中,它最终会崩溃。

这是我尝试的:

path = easygui.diropenbox() #Easygui is used to get a path in order to save the file to the right place
dfA = pd.DataFrame(A) #the pandas dataframe
C = ['Gen','Density','ASPL','Modularity'] # pandas' excel file header
name = str(n) + "_" + str(NGEN) + "_" + str(nbrhof) + ".xls" # the name of the file (should I add the path here somewhere?)
dfA.to_excel(name, path, header=C,index=False) # exporting the dataframe to excel

我可以修改此脚本以从 py2app 编译的应用程序中将名为“name”的 excel 文件保存到使用“easygui.diropenbox()”选择的文件夹中吗?

回溯如下:

Traceback (most recent call last):
File "/Users/myself/Dropbox/Python/Tests/test2/myscript.py", line 135, in <module>
nx.write_gexf(G, path, name+".gexf")
File "<string>", line 2, in write_gexf
File "/Library/Python/2.7/site-packages/networkx-1.8.1-py2.7.egg/networkx/utils/decorators.py", line 241, in _open_file
fobj = _dispatch_dict[ext](path, mode=mode)
IOError: [Errno 21] Is a directory: '/Users/Rodolphe/Desktop/chosenfolder'
[Finished in 65.5s with exit code 1]
[shell_cmd: python -u "/Users/myself/Dropbox/Python/Tests/test2/myscript.py"]
[dir: /Users/Rodolphe/Dropbox/Python/Tests/test2]
[path: /usr/bin:/bin:/usr/sbin:/sbin]
4

1 回答 1

2

这是一个工作版本:

import pandas as pd
import easygui
import os

A = {'one' : pd.Series([1., 2., 3.], index=['a', 'b', 'c']),
     'two' : pd.Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd'])}
dfA = pd.DataFrame(A) #the pandas dataframe

path = easygui.diropenbox() # easygui is used to get a path
name = "tmp.xlsx" # the name of the file
path = os.path.join(path, name)  # this is the full pathname
dfA.to_excel(path, 'tmp_sheet') # exporting the dataframe to excel

请注意,该to_excel()方法的初始参数是您正在编写的 Excel 工作表的完整路径名,第二个参数是工作表的名称。

此外,您的堆栈跟踪似乎是指脚本的另一部分,并且可能指向另一个错误。

于 2013-12-10T12:35:40.497 回答