压缩 python 中的目录或文件

Zipping Directory or file(s) in 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)

我对您的代码做了如下修改:

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) 

祝你好运!