2016-06-01 8 views
0

Im folgenden Code muss ich package.inf direkt in die Zip-Datei schreiben, die am Ende des Skripts erstellt wird.Textdatei in eine Zip-Datei ohne temporäre Dateien schreiben

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

schreiben pakInf in themePak ohne temporäre Dateien.

+0

könnten Sie 'StringIO' und' BytesIO' vom 'io' Modul. – Squall

+0

@Squall Konnte ich das bitte im Antwortformat mit einem Beispiel haben, um mich zu beginnen? So etwas habe ich noch nie gemacht. – spikespaz

Antwort

1

Verwenden io.StringIO ein dateiähnliche Objekt im Speicher zu erstellen:

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