首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >Python 3:正确格式化zip模块参数(newb)

Python 3:正确格式化zip模块参数(newb)
EN

Stack Overflow用户
提问于 2009-04-05 19:16:12
回答 2查看 1.3K关注 0票数 1

请告诉我为什么这个代码会失败。我是新手,我不明白为什么我的zip参数的格式不正确。由于我不确定如何更好地沟通,所以我将显示代码、错误消息以及我认为正在发生的事情。

代码语言:javascript
代码运行次数:0
运行
复制
#!c:\python30
# Filename: backup_ver5.py

import os
import time
import zipfile


source = r'"C:\Documents and Settings\Benjamin Serrato\My Documents\python\backup_list"'

target_dir = r'C:\Documents and Settings\Benjamin Serrato\My Documents\python\backup_dir'

today = target_dir + os.sep + time.strftime('%Y%m%d') 

now = time.strftime('%H%M%S')

comment = input('Enter a comment --> ')

if len(comment) == 0:
    target = '"' + today + os.sep + now + '.zip' + '"'
else:
    target = '"' + today + os.sep + now + '_' + \
    comment.replace(' ', '_') + '.zip' + '"'

if not os.path.exists(today):
    os.mkdir(today)
    print('Successfully created directory', today)


print(target)
print(source)
zip_command = zipfile.ZipFile(target, 'w').write(source)

if os.system(zip_command) == 0:
    print('Successful backup to', target)
else:
    print('Backup FAILED')

    enter code here

我收到以下错误消息:

代码语言:javascript
代码运行次数:0
运行
复制
Enter a comment -->
"C:\Documents and Settings\Benjamin Serrato\My Documents\python\backup_dir\20090
405\134614.zip"
"C:\Documents and Settings\Benjamin Serrato\My Documents\python\backup_list"
Traceback (most recent call last):
  File "C:\Documents and Settings\Benjamin Serrato\My Documents\python\backup_ve
r5.py", line 32, in <module>
    zip_command = zipfile.ZipFile(target, 'w').write(source)
  File "c:\python30\lib\zipfile.py", line 683, in __init__
    self.fp = io.open(file, modeDict[mode])
  File "C:\Python30\lib\io.py", line 222, in open
    closefd)
  File "C:\Python30\lib\io.py", line 615, in __init__
    _fileio._FileIO.__init__(self, name, mode, closefd)
IOError: [Errno 22] Invalid argument: '"C:\\Documents and Settings\\Benjamin Ser
rato\\My Documents\\python\\backup_dir\\20090405\\134614.zip"'

在分配zip_command之前的两个打印测试告诉我,这两个字符串被正确地传递给了zipfile.ZipFile()。回溯告诉我没有正确调用zipfile.ZipFile()__init__中的错误让我更加确信这一点。最后,问题似乎是我导致我的路径字符串有双反斜杠。我不明白为什么IOError会显示这一点。

我使用了this site来了解如何使用zipfilezipfile是一个类,我在程序开始时导入它,然后使用它和它的主要方法。我将想要写入的文件传递给zipfile.ZipFile('file to write', 'mode'),并将程序设置为打开一个设置为可写的对象。然后,该命令使用类似于"".zipfile('files to write')的子方法将文件写入目标文件夹。

我哪里错了?

EN

回答 2

Stack Overflow用户

发布于 2009-04-05 19:21:44

看起来是因为你的路径名周围多了一对双引号。去掉双引号,看看它是否起作用。

票数 3
EN

Stack Overflow用户

发布于 2009-04-05 19:24:31

回答你的另一个问题:有双反斜杠是因为它们是escaped

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/719503

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档