umb*_*987 0 python string binary save
我想知道Python编程的一个非常基本的东西,因为我现在是一个非常基本的程序员):如何在Python中将结果(列表,字符串或其他)保存到文件中?我一直在搜索,但我找不到任何好的答案.我正在考虑".write()"方法,但是(例如)它似乎没有使用字符串,我也不知道它应该做什么.所以,我的情况是我有二进制文件,我想编辑,因此我发现很容易将它们转换为字符串,修改它们,现在我想保存它们i)回到二进制文件(jpegs图像)和ii)在我想要的文件夹中.我该怎么办?我需要一些帮助.
UPDATE
这是我正在尝试运行的脚本:
import os, sys
newpath= r'C:/Users/Umberto/Desktop/temporary'
if not os.path.exists (newpath):
os.makedirs (newpath)
data= open ('C:/Users/Umberto/Desktop/Prove_Script/Varie/_BR_Browse.001_2065642654_1.BINARY', 'rb+')
edit_data= str (data.read () )
out_dir= os.path.join (newpath, 'feed', 'address')
data.close ()
# do my edits in a secon time...
edit_data.write (newpath)
edit_data.close ()
Run Code Online (Sandbox Code Playgroud)
我得到的错误是:
AttributeError: 'str' object has no attribute 'write'
Run Code Online (Sandbox Code Playgroud)
UPDATE_2
我尝试使用pickle模块来序列化我的二进制文件,修改它并在最后保存它,但仍然没有让它工作......这是我到目前为止所尝试的:
import cPickle as pickle
binary= open ('C:\Users\Umberto\Desktop\Prove_Script\Varie\_BR_Browse.001_2065642654_1.BINARY', 'rb')
out= open ('C:\Users\Umberto\Desktop\Prove_Script\Varie\preview.txt', 'wb')
pickle.dump (binary, out, 1)
TypeError Traceback (most recent call last)
<ipython-input-6-981b17a6ad99> in <module>()
----> 1 pprint.pprint (pickle.dump (binary, out, 1))
C:\Python27\ArcGIS10.1\lib\copy_reg.pyc in _reduce_ex(self, proto)
68 else:
69 if base is self.__class__:
---> 70 raise TypeError, "can't pickle %s objects" % base.__name__
71 state = base(self)
72 args = (self.__class__, base, state)
TypeError: can't pickle file objects
Run Code Online (Sandbox Code Playgroud)
我没有得到的另一件事是,如果我应该创建一个文件来poit(在我的情况下我必须创建"out",否则我没有正确的参数pickle方法)或它是没有必要的.希望我能接近解决方案.
PS:我也尝试过pickle.dumps(),虽然没有取得更好的结果......
如果您打开二进制文件并保存另一个二进制文件,则可以执行以下操作:
with open('file.jpg', 'rb') as jpgFile:
contents = jpgFile.read()
contents = (some operations here)
with open('file2.jpg', 'wb') as jpgFile:
jpgFile.write(contents)
Run Code Online (Sandbox Code Playgroud)
一些评论:
如果您需要保存列表,字符串或其他对象,并在以后检索它们,请使用pickle,就像其他人指出的那样.