如何将列表保存到临时目录中的pickle文件并将该文件传递给函数?

时间:2014-04-26 05:19:57

标签: python directory save dropbox pickle

问题是我从一个来源提取数据,我想将它作为pickle文件保存到Dropbox。我无法将其保存在目录中,因为我在服务器上运行代码(iron.io)。

import tempfile
import pickle


def SFDCDropboxSync(Data):
   f = tempfile.NamedTemporaryFile(delete=False)
   pickle.dump(Data,open(f,'wb'))

   client = dropbox.client.DropboxClient(access_token)
   client.put_file(filename, f)

这是我得到的错误:

Traceback (most recent call last):   File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Shippy/RecurringDataDump/SFDCDropboxUpload.py", line 38, in <module>
    if __name__ == "__main__": main()   File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Shippy/RecurringDataDump/SFDCDropboxUpload.py", line 31, in main
    print SFDCDropboxUploadDownload().SFDCDropboxSync(lst)   File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Shippy/RecurringDataDump/SFDCDropboxUpload.py", line 26, in SFDCDropboxSync
    pkl = self.SaveListtoPickle(lst)   File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Shippy/RecurringDataDump/SFDCDropboxUpload.py", line 20, in SaveListtoPickle
    pickle.dump(lst,open(f,'wb')) TypeError: coercing to Unicode: need string or buffer, instance found [Finished in 0.7s with exit code 1] [shell_cmd: python -u "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Shippy/RecurringDataDump/SFDCDropboxUpload.py"] [dir: /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Shippy/RecurringDataDump] [path: /usr/bin:/bin:/usr/sbin:/sbin]

1 个答案:

答案 0 :(得分:2)

在您的代码中,NamedTemporaryFile f不是字符串。它是一个文件对象,类似于open(file_path)的输出。

来自documentation:这个类似文件的对象可以在with语句中使用,就像普通文件一样。

如果要转到创建的文件,请使用tmp_file.name

例如,这有效:(在python 3.6.2上测试)

def SFDCDropboxSync(Data):
    with tempfile.NamedTemporaryFile() as tmp_file:
        pickle.dump(Data, tmp_file)
        tmp_file.flush()

        print(pickle.load(open(tmp_file.name, 'rb')))

这将在文件退出时删除文件(文件关闭)。

警告Windows :您可能无法在文件打开时阅读该文件。相反,使用类似的东西:

with tempfile.NamedTemporaryFile(delete=False) as tmp_file:
    pickle.dump(Data, open(tmp_file.name, 'wb'))
    tmp_filename = tmp_file.name

pickle.load(open(tmp_filename, 'rb'))
os.remove(tmp_filename)