2015-09-23 106 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) 

祝您好运!