在python中压缩目录或文件

时间:2015-09-23 05:00:06

标签: python-2.7 zip

我正在尝试压缩目录中存在的文件并为其指定特定名称(目标文件夹)。我想将源文件夹和目标文件夹作为输入传递给程序。

但是,当我正在经历源文件路径时,它会给我和错误。我想我将面临与目标文件路径相同的问题。

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 个答案:

答案 0 :(得分: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) 

祝你好运!