将文本文件写入不带临时文件的zip文件

时间:2016-06-01 19:23:00

标签: python python-3.x zip zipfile

在下面的代码中,我需要将package.inf直接转到脚本底部创建的zip文件中。

import os
import zipfile

print("Note: All theme files need to be inside of the 'theme_files' folder.")
themeName = input("\nTheme name: ")
themeAuthor = input("\nTheme author: ")
themeDescription = input("\nTheme description: ")
themeContact = input("\nAuthor contact: ")
otherInfo = input("\nAdd custom information? y/n: ")
if otherInfo == "y":
    os.system("cls" if os.name == "nt" else "clear")
    print("\nEnter extra theme package information below.\n--------------------\n")
    themeInfo = input()

pakName = themeName.replace(" ", "_").lower()

pakInf = open("package.inf", "w")
pakInf.write("Theme name: "+ themeName +"\n"+"Theme author: "+ themeAuthor +"\n"+"Theme description: "+ themeDescription +"\n"+"Author contact: "+ themeContact)
if otherInfo == "y":
    pakInf.write("\n"+ themeInfo)

pakInf.close()

themePak = zipfile.ZipFile(pakName +".tpk", "w")
for dirname, subdirs, files in os.walk("theme_files"):
    themePak.write(dirname)
    for filename in files:
        themePak.write(os.path.join(dirname, filename))

themePak.close()

pakInf写入themePak而不创建任何临时文件。

1 个答案:

答案 0 :(得分:1)

使用io.StringIO在内存中创建类似文件的对象:

import io
import os
import zipfile

print("Note: All theme files need to be inside of the 'theme_files' folder.")
themeName = input("\nTheme name: ")
themeAuthor = input("\nTheme author: ")
themeDescription = input("\nTheme description: ")
themeContact = input("\nAuthor contact: ")
otherInfo = input("\nAdd custom information? y/n: ")
if otherInfo == "y":
    os.system("cls" if os.name == "nt" else "clear")
    print("\nEnter extra theme package information below.\n--------------------\n")
    themeInfo = input()

pakName = themeName.replace(" ", "_").lower()

pakInf = io.StringIO()
pakInf.write("Theme name: "+ themeName +"\n"+"Theme author: "+ themeAuthor +"\n"+"Theme description: "+ themeDescription +"\n"+"Author contact: "+ themeContact)
if otherInfo == "y":
    pakInf.write("\n"+ themeInfo)

themePak = zipfile.ZipFile(pakName +".tpk", "w")
themePak.writestr("package.inf", pakInf.getvalue())
for dirname, subdirs, files in os.walk("theme_files"):
    themePak.write(dirname)
    for filename in files:
        themePak.write(os.path.join(dirname, filename))

themePak.close()