2013-03-02 132 views
0

python新手,一直在写这个大概一个小时。 Google文档api和示例非常棒。我可以连接并创建文件等。我想将我的所有文件备份到谷歌驱动器,因此尝试使用os.walk,并遇到了我不明白的持续缩进错误。python缩进错误

#!/usr/bin/python 

import httplib2 
import pprint 
from apiclient.discovery import build 
from apiclient.http import MediaFileUpload 
from oauth2client.client import OAuth2WebServerFlow 
from oauth2client.client import Credentials 
import os 
import sys 

rootdir = sys.argv[1] 

CLIENT_ID = 'MYCLIENT ID' 
CLIENT_SECRET = 'MY SECRET ID' 
OAUTH_SCOPE = 'https://www.googleapis.com/auth/drive' 

# Redirect URI for installed apps 
REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob' 

json_creds = open('backup_credentials.json', 'r').read() 
credentials = Credentials.new_from_json(json_creds) 
# 
# Create an httplib2.Http object and authorize it with our credentials 
http = httplib2.Http() 
http = credentials.authorize(http) 
drive_service = build('drive', 'v2', http=http) 

#Here is where the problem starts 
for root, subFolders, files in os.walk(rootdir): 
    for filename in files: 
     filepath = os.path.join(root, filename) 
     print (filepath) 
     media_body = MediaFileUpload(filepath, mimetype='text/plain', resumable=True) 
     body = {'title': filename,'description': 'A test document','mimeType': 'text/plain'} 
     file = drive_service.files().insert(body=body, media_body=media_body).execute() 
     pprint.pprint(file) 

的违规错误行文件= ...

实际的错误是

File "./quickstart.py", line 59 
    file = drive_service.files().insert(body=body, media_body=media_body).execute() 
                      ^
IndentationError: unindent does not match any outer indentation level 
+0

您的缩进在'body = {' – 2013-03-02 04:26:02

+4

之后关闭不要混合制表符和空格。 [PEP 8](http://www.python.org/dev/peps/pep-0008/#tabs-or-spaces)说:“千万不要混合制表符和空格。 缩进Python最流行的方式是用空格第二种最流行的方式是仅使用制表符,缩进和制表符混合使用的代码应该转换为仅使用空格**当使用-t选项调用Python命令行解释器时,它会发出有关代码的警告非法混合制表符和空格**使用-tt时,这些警告会变成错误,强烈建议使用这些选项!“ – 2013-03-02 04:36:44

回答

6

你有

body = { 
    'title': filename, 
    'description': 'A test document', 
    'mimeType': 'text/plain' 
    } 
    file = drive_service.files().insert(body=body, media_body=media_body).execute() 
    pprint.pprint(file) 

时,你应该有:

body = { 
    'title': filename, 
    'description': 'A test document', 
    'mimeType': 'text/plain' 
    } 
    file = drive_service.files().insert(body=body, media_body=media_body).execute() 
    pprint.pprint(file) 

请注意,file =行应缩进到与缩进行“上面”的行相同的级别(body = ...)。

+0

谢谢。其实试图将代码粘贴到stackoverflow搞砸了原始的缩进。如果有一个简单的方法来粘贴python代码将会很棒。我有这样的意图,但它仍然没有奏效。所以我最终将body = {}的所有内容合并为一行,现在我没事了。在python中,如果你打算做一些像body一样的多行代码,你是否必须逃避它,或者做些特别的事情,否则会搞砸你的想法? – glacierDiscomfort 2013-03-02 04:34:48

+0

@glacier不舒服 - 把它分成多行就好了。在python中,任何未终止的大括号,括号和括号都会自动转换为单行。 – mgilson 2013-03-02 04:36:17

+0

[隐含行加入](http://docs.python.org/2/reference/lexical_analysis.html#implicit-line-joining)详细解释了mgilson提到的内容。 – 2013-03-02 04:39:32