试图将文件存储在字符串python中

时间:2014-12-22 15:46:13

标签: python pickle software-distribution

这是我的第一个python项目之一,我正在尝试编写一个脚本来编写一个可以重新创建src /目录的脚本。这将是我分发给用户的内容。它使用walk,并写入首先创建所有目录的python文件,然后写入文件。我的问题是将文件变成一个我可以写入文件的字符串。

这是我的程序:

import os
import pickle

src = os.path.dirname(os.path.realpath(__file__)) + os.sep + 'src'
fPack = 'import os \nimport pickle \nmyDir = os.path.dirname(os.path.realpath(__file__))'
Pack =''
print 'Packing ' + src
pickle
for root, dirs, files in os.walk(src, topdown=True):
    for name in files:
        print os.path.join(root, name)
        f = open(os.path.join(root, name), 'r')
        Pack = Pack + '\nf = open(os.path.join(myDir,\'' + name + '\'), \'w\')'
        fileCont = pickle.dumps(f.read())
        Pack = Pack + '\nf.write(pickle.loads(\'' + fileCont + '\'))'
    for name in dirs:
        print os.path.join(root, name)
        fPack = fPack + '\nos.makedirs(os.path.join(myDir,\'' + name + '\'))'

print '==================================================\n\n\n'
print fPack + Pack 
f = open(os.getcwd() + os.sep + 'dist' + os.sep + 'Pack.py', 'w')
f.write(fPack)
f.write(Pack)

如果我在一个带有on子目录的目录中运行它,并在文件里面创建这个文件

import os 
import pickle 
myDir = os.path.dirname(os.path.realpath(__file__))
os.makedirs(os.path.join(myDir,'SphereText'))
f = open(os.path.join(myDir,'TextMain.py'), 'w')
f.write(pickle.loads('S"########################################################\n#Main SphereText file.                                 #\n#SpereText is a simple Notepad-Like plain text editor  #\n########################################################\n\nfrom Tkinter import *\nfrom tkFileDialog import *\nimport tkSimpleDialog\n\nroot = Tk()\nroot.title('SphereText')\n\ndef fSave():\n    fileName = asksaveasfilename(parent=root)\n    f = open(fileName, 'w')\n    f.write(text.get(1.0,END))\n\ndef fOpen():\n    fileName = ''\n    fileName = askopenfilename(parent=root)\n    f = open(fileName, 'r')\n    text.delete(1.0,END)\n    text.insert(1.0, f.read())\n\ndef tReplace():\n        Old = tkSimpleDialog.askstring('SphereText', 'Replace:')\n        print Old\n        New = tkSimpleDialog.askstring('SphereText', 'With:')\n        print New\n        content = text.get(1.0,END)\n        content = content.replace(Old, New)\n        text.delete(1.0,END)\n        text.insert(1.0, content)\n    \nmenubar = Menu(root)\nmenubar.add_command(label='Save', command=fSave)\nmenubar.add_command(label='Open', command=fOpen)\nmenubar.add_command(label='Replace', command=tReplace)\nroot.config(menu=menubar)\n\ntext = Text(root, wrap=WORD)\n\ntext.pack()\n\nroot.mainloop()\n"
p0
.'))

没有逃脱,最后有两个换行符。我认为序列化的全部意义在于你总能以同样的方式阅读它。任何人都知道我怎么能把文件变成有效的字符串?

1 个答案:

答案 0 :(得分:0)

对于这个新问题我很抱歉,我发现我一直试图重新发明轮子。显然,这已经存在于Squeeze的名下。