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



在下面的代码中,我需要直接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,而不创建任何临时文件。

使用 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()