我试图将一个基本的备份脚本从一个文件夹写到另一个文件夹,然后让它工作 - 但目录结构没有被复制,只是文件。我也尝试复制子文件夹,例如,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
答案 0 :(得分:4)
答案 1 :(得分:1)
此错误通常表示缩进时出错。检查您不要混合标签和空格。
您可以使用https://www.pylint.org/来检测它们,或者只需将代码粘贴到http://pep8online.com,它就会显示您可以增强的内容。
答案 2 :(得分:0)
更改
if subdir == source_folder :
带
if subdir == source_folder: