学习python并遇到第一个程序的问题

Nyr*_*bie 2 python

我编写了这段代码,它在第11行失败了"target_dir"命令,语法无效我有一个vm ubuntu,我只是复制并粘贴了代码,它在那里工作但不在我的win7中,我不知道为什么.我正在阅读另一个类似代码的问题,但它有一个不同的错误,并注意到有人说这些命令中的一些已经过时,所以我只是想知道是否是这样,我会放弃这本书然后转到另一个我只是拿到.

在此先感谢您的帮助,

# Filename: backup_ver1.py

import os
import time

# 1. The files and directories to be backed up are specified in a list.
source = ['"D:\\Warlock"', 'C:\\Druid'
# Notice we had to use double quotes inside the string for names with spaces in it.

# 2. The backup must be stored in a main backup directory
target_dir = r'C:\Backup' # Remember to change this to what you will be using


# 3. The files are backed up into zip file.
# 4. The name of the zip archive is the current date and time
target = target_dir + os.sep + time.strftime('%Y%m%d%H%M%S') + '.zip'

# 5. We use the zip commnad to put the files in a zip archive
zip_commnad = "7z a -tzip {0} {1}" .format(target, ' '.join(source))
    print(zip_command)

#Run the backup
if os.system(zip_command) == 0:
    print('Successful backup', target)
else:
    print('Backup FAILED')
Run Code Online (Sandbox Code Playgroud)

Bla*_*air 7

source = ['"D:\\Warlock"', 'C:\\Druid'缺少一个结束括号.应该source = ['"D:\\Warlock"', 'C:\\Druid'].

编辑:此外,

zip_commnad = "7z a -tzip {0} {1}" .format(target, ' '.join(source))
    print(zip_command)
Run Code Online (Sandbox Code Playgroud)

应该

zip_command = "7z a -tzip {0} {1}" .format(target, ' '.join(source))
print(zip_command)
Run Code Online (Sandbox Code Playgroud)

即拼写命令正确并修复缩进.另外,尽管像你这样定义备份路径并不是一个错误,但我同意abaumg的观点,即使用原始字符串会更加清晰.

  • 为了更好的可读性,我建议`source = [r'D:\ Warlock',r'C:\ Druid']` (3认同)