我正在尝试实现一个从用户的Dropbox帐户下载文件的Dropbox应用程序。在用户的本地目录中创建目标路径时,它会崩溃说
发生错误[400] {u'path:u''invalid path / New folder \\ img1.jpg:不允许索引11反斜杠的字符}
我认为dropbox的文件夹层次结构使用正斜杠来表示dorectories的嵌套,而windows使用反斜杠,因此它们可能存在冲突。然后我使用python的BIF replace(),如下所示,用于不同的路径
sample_path.replace(“\\”,“/”)
但仍然
我的代码中的complete_path
变量给出包含反斜杠的路径,之后程序崩溃。 我的保管箱帐户中的文件夹层次结构为:
New Folder :
Img1.jpg
dtu.jpg
img.jpg
代码是:
def download_file(self,source_path,target_path):
print 'Downloading %s' % source_path
file_path = os.path.expanduser(target_path)
(dir_path,tail) = os.path.split(target_path)
self.check_dir(dir_path)
to_file = open(file_path,"wb")
print source_path+"!!!!!!!!!!!!!!!!!!!!!!!!!!"
source_path.replace("\\","/")
f= self.mClient.get_file(source_path) # request to server !
to_file.write(f.read())
return
def download_folder(self, folderPath):
# try to download 5 times to handle http 5xx errors from dropbox
try:
response = self.mClient.metadata(folderPath)
# also ensure that response includes content
if 'contents' in response:
for f in response['contents']:
name = os.path.basename(f['path'])
complete_path = os.path.join(folderPath, name)
if f['is_dir']:
# do recursion to also download this folder
self.download_folder(complete_path)
else:
# download the file
self.download_file(complete_path, os.path.join(self._target_folder, complete_path))
else:
raise ValueError
except (rest.ErrorResponse, rest.RESTSocketError, ValueError) as error:
print 'An error occured while listing a directory. Will try again in some seconds.'
print "Error occured "+ str(error)
答案 0 :(得分:3)
在Python控制台中尝试使用此功能来查看问题:
>>> x = "hello"
>>> x.replace("hello", "goodbye")
'goodbye'
>>> x
'hello'
在字符串上调用replace
实际上并不会修改字符串。它返回一个带有替换的新字符串。所以你可能想要这样做:
source_path = source_path.replace("\\", "/")