新手需要Python教程的帮助
我刚开始学习Python(3.0),这是我用过的第一门编程语言。我现在卡在一个简单的程序上,这个程序是用来创建一个备份的zip文件(第75页)。我在使用Windows 7(64位)和Python 3.1。在这之前,我安装了GNUWin32和源代码,并把C:\Program Files(x86)\GnuWin32\bin添加到了我的Path环境变量中。下面是我的程序:
#!C:\Python31\mystuff
# Filename : my_backup_v1.py
import os
import time
# backing up a couple small files that I made
source = [r'C:\AB\a', r'C:\AB\b']
#my back up directory
target_dir = 'C:\\Backup'
#name of back up file
target = target_dir + os.sep + time.strftime('%Y%m%d%H%M%S') + '.zip'
zip_command = "zip -qr {0} {1}".format(target,' '.join(source))
print(zip_command)
if os.system(zip_command) == 0:
print('Successful backup to', target)
else:
print('Backup failed!')
print('source files are', source)
print('target directory is', target_dir)
print('target is', target)
输出结果:
zip -qr C:\Backup\20100106143030.zip C:\AB\a C:\AB\b
Backup failed!
source files are ['C:\\AB\\a', 'C:\\AB\\b']
target directory is C:\Backup
target is C:\Backup\20100106143030.zip
这个教程里有一点故障排除的建议:把zip_command复制粘贴到Python的命令行提示符里,看看至少能不能工作:
>>> zip -qr C:\Backup\20100106143030.zip C:\AB\a C:\AB\b
SyntaxError: invalid syntax (<pyshell#17>, line 1)
但是这并没有成功,教程建议我去阅读GNUWin32的手册以获得更多帮助。我翻了翻手册,但还没找到能帮到我的内容。为了检查zip功能是否正常,我输入了help(zip),得到了以下信息:
>>> help(zip)
Help on class zip in module builtins:
class zip(object)
| zip(iter1 [,iter2 [...]]) --> zip object
|
| Return a zip object whose .__next__() method returns a tuple where
| the i-th element comes from the i-th iterable argument. The .__next__()
| method continues until the shortest iterable in the argument sequence
| is exhausted and then it raises StopIteration.
|
| Methods defined here:
|
| __getattribute__(...)
| x.__getattribute__('name') <==> x.name
|
| __iter__(...)
| x.__iter__() <==> iter(x)
|
| __next__(...)
| x.__next__() <==> next(x)
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __new__ = <built-in method __new__ of type object at 0x1E1B8D80>
| T.__new__(S, ...) -> a new object with type S, a subtype of T
可惜我还不太理解这个“帮助”内容。不过我试着玩了一下zip功能,看看它是怎么工作的。
>>> zip (r'C:AB\a')
<zip object at 0x029CE8C8>
看起来zip功能是可以用的,但我想我可能没有正确使用它。请帮帮我,记住我在编程方面的经验还不多。如果你想查看这个教程,可以在www.swaroopch.com/notes/Python找到。
4 个回答
这段话的意思是,你看到的帮助信息不是关于命令行中用的 zip
命令,而是关于 Python 里的 zip
函数。这两个东西没有关系,前者是用来压缩文件的,后者则是用来处理数据的。
>>> zip -qr C:\Backup\20100106143030.zip C:\AB\a C:\AB\b
听起来像是你应该在操作系统的命令行里输入的命令,而不是在Python的命令行里。你可以试试
os.system('zip -qr C:\Backup\20100106143030.zip C:\AB\a C:\AB\b')
在Python的命令行里...
你输入的命令 "zip -qr C:\Backup\20100106143030.zip C:\AB\a C:\AB\b
" 在命令行中失败了,因为这里的 "zip" 是一个你要发送给操作系统的命令,跟Python没有关系。
这可能有点让人困惑。当你输入 "zip(r'C:AB\a')
" 时,其实是在使用Python自带的 zip()
函数,这和你想做的事情没有任何关系。
你确认一下你的文件夹结构是否正确吗?也就是说,C:\AB\a 和 C:\AB\b 这两个文件夹存在吗?
补充说明 - 你应该把那个长长的 "zip" 命令复制粘贴到命令提示符中(按下Windows键 + R,然后输入 "cmd" 并按回车),看看能不能成功;而不是在Python的命令行里。