2015-09-23 145 views
0

我想壓縮目錄中的文件並給它一個特定的名稱(目標文件夾)。我想將源文件夾和目標文件夾作爲輸入傳遞給程序。在python中壓縮目錄或文件

但是,當我走過源文件路徑它給我和錯誤。我想我會面對與目標文件路徑相同的問題。

d:\SARFARAZ\Python>python zip.py 
Enter source directry:D:\Sarfaraz\Python\Project_Euler 
Traceback (most recent call last): 
    File "zip.py", line 17, in <module> 
    SrcPath = input("Enter source directry:") 
    File "<string>", line 1 
    D:\Sarfaraz\Python\Project_Euler 
    ^
SyntaxError: invalid syntax 

我寫的代碼如下:

import os 
import zipfile 

def zip(src, dst): 
    zf = zipfile.ZipFile("%s.zip" % (dst), "w", zipfile.ZIP_DEFLATED) 
    abs_src = os.path.abspath(src) 
    for dirname, subdirs, files in os.walk(src): 
     for filename in files: 
      absname = os.path.abspath(os.path.join(dirname, filename)) 
      arcname = absname[len(abs_src) + 1:] 
      print 'zipping %s as %s' % (os.path.join(dirname, filename),arcname) 
      zf.write(absname, arcname) 
    zf.close() 

#zip("D:\\Sarfaraz\\Python\\Project_Euler", "C:\\Users\\md_sarfaraz\\Desktop") 

SrcPath = input("Enter source directry:") 
SrcPath = ("@'"+ str(SrcPath) +"'") 
print SrcPath # checking source path 
DestPath = input("Enter destination directry:") 
DestPath = ("@'"+str(DestPath) +"'") 
print DestPath 
zip(SrcPath, DestPath) 

回答

1

我已經做出了一些改變你的代碼如下:

import os 
import zipfile 

def zip(src, dst): 
    zf = zipfile.ZipFile(dst, "w", zipfile.ZIP_DEFLATED) 
    abs_src = os.path.abspath(src) 
    for dirname, subdirs, files in os.walk(src): 
     for filename in files: 
      absname = os.path.abspath(os.path.join(dirname, filename)) 
      arcname = absname[len(abs_src) + 1:] 
      print 'zipping %s as %s' % (os.path.join(dirname, filename),arcname) 
      zf.write(absname, arcname) 
    zf.close() 


# Changed from input() to raw_input() 
SrcPath = raw_input("Enter source directory: ") 
print SrcPath # checking source path 

# done the same and also added the option of specifying the name of Zipped file. 
DestZipFileName = raw_input("Enter destination Zip File Name: ") + ".zip" # i.e. test.zip 
DestPathName = raw_input("Enter destination directory: ") 
# Here added "\\" to make sure the zipped file will be placed in the specified directory. 
# i.e. C:\\Users\\md_sarfaraz\\Desktop\\ 
# i.e. double \\ to escape the backlash character. 
DestPath = DestPathName + "\\" + DestZipFileName 
print DestPath # Checking Destination Zip File name & Path 
zip(SrcPath, DestPath) 

祝您好運!