python脚本期望if语句中的缩进块

时间:2016-06-22 17:47:00

标签: python

我试图将一个基本的备份脚本从一个文件夹写到另一个文件夹,然后让它工作 - 但目录结构没有被复制,只是文件。我也尝试复制子文件夹,例如,c:\temp\docs\file.txt转到d:\temp\docs\file.txt而不只是d:\temp\file.txt

我的问题存在于if / else语句的缩进中,但一切对我来说都很好。我做错了什么?

import datetime, time, string, os, shutil

COPY_FROM_LOCATION = 'C:\\xampp\\htdocs\\projects'
folder_date = time.strftime("%Y-%m-%d")
BACKUP_TO_LOCATION = 'D:\\BACKUP\\' + folder_date

#Create a new directory in D:\BACKUP based on today's date so the folder you're trying to copy to actually exists:
if not os.path.exists(BACKUP_TO_LOCATION):
    os.makedirs(BACKUP_TO_LOCATION)

#copy function
def backup(source_folder, target_folder):
    for subdir, dirs, files in os.walk(source_folder):
        if subdir == source_folder :
            new_target_folder = target_folder
        else:
            folder_name = subdir.split("C:\\xampp\\htdocs\\projects\\",1)[-1]
            new_target_folder = target_folder + "\\" + folder_name
        for file in files:
            print "backing up: " + folder_name
            shutil.copy2(os.path.join(subdir, file), new_target_folder) 

backup(COPY_FROM_LOCATION,BACKUP_TO_LOCATION)

这是我得到的错误:

  File "backup.py", line 15
    new_target_folder = target_folder
                    ^
IndentationError: expected an indented block

3 个答案:

答案 0 :(得分:4)

你正在混合制表符和空格。

enter image description here

使用其中一个,而不是两个。最好是空格。

答案 1 :(得分:1)

此错误通常表示缩进时出错。检查您不要混合标签空格

您可以使用https://www.pylint.org/来检测它们,或者只需将代码粘贴到http://pep8online.com,它就会显示您可以增强的内容。

答案 2 :(得分:0)

什么与分号前空间的奇怪之处是什么?我之前没见过它,这似乎是这个剧本窒息的地方。

更改

if subdir == source_folder :

if subdir == source_folder:
相关问题