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