我正在根据用户的输入编写zipFile多个文件的代码。 例如,用户键入几个文件路径,例如C:\ Users \ AAA \ BBB,C:\ Users \ AAA \ CCC,...程序将所有这些文件备份到一个新的zip文件中。
现在我正在使用一个循环(来自"而True"的代码)并且它有效。但这只允许我们每次输入一条路径。有一种巧妙的方法,我们可以一次输入所有路径并将它们添加到列表中(文件列表在这里)?
当我刚开始使用Python并且我基于#34; A Byte of Python"编写它时,我觉得我的代码有点冗长......请随时提供改进它的建议。谢谢。
import os,time,zipfile
def createZip():
# Define the file path to save the file
savePath=input('Enter file save path-->')
if len(savePath)==0:
print('No path is found. Backup ends.')
# Define the file to be saved
else:
assert os.path.exists(savePath),"File path does not exist. Backup fails." # assert expression1, expression2, equals to if not expression1, raise AssertionError(expression2)
fileList=[]
while True:
filePath=input('Enter files to save. Enter "Done" to end.-->')
if filePath=='Done':
break
else:
if len(filePath)==0:
print('No path is found. Please enter files to save.')
else:
assert os.path.exists(filePath),"File path does not exist. Backup fails."
fileList.append(filePath)
today=savePath+os.sep+time.strftime('%Y%m%d')
now=time.strftime('%H%M%S')
if not os.path.exists(today):
os.mkdir(today)
print('Successfully created directory', today)
comment=input('Enter a comment -->')
if len(comment)==0:
target=today+os.sep+now+'.zip'
else:
target=today+os.sep+now+'_'+comment+'.zip'
newZip=zipfile.ZipFile(target,'w',zipfile.ZIP_DEFLATED) # 'w' means write only; 'r' means read only
for fName in fileList:
for root,dirs,files in os.walk(fName):
for file in files:
newZip.write(os.path.join(root,file))
newZip.close()
print('backup to',target)
createZip()
答案 0 :(得分:0)
它很容易。您可以拆分用户输入的文本,但您需要担心名称中包含空格的文件。 shlex
允许您以类似于unix的shell的方式拆分一条线,从而为您提供所需的规则。
import shlex
fileList = []
while True:
filePaths = input('Enter files to save. Enter "Done" to end.-->')
if filePaths.lower() == "done":
break
for filePath in shlex.split(filePaths):
if not os.path.exists(filePath):
print("'{}' not found".format(filePath))
else:
fileList.append(filePath)