问题描述
我正在驱动器中的文件夹中下载文件,并且我想将它们也存储在我的python脚本所在位置的本地文件夹中,而不是将它们保存在没有文件夹的情况下,我当前的代码在这里:
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import io
from googleapiclient.http import MediaIoBaseDownload
# If modifying these scopes,delete the file token.pickle.
ScopES = ['https://www.googleapis.com/auth/drive.file','https://www.googleapis.com/auth/drive']
def main():
creds = None
# The file token.pickle stores the user's access and refresh tokens,and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle','rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available,let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json',ScopES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle','wb') as token:
pickle.dump(creds,token)
service = build('drive','v3',credentials=creds)
# Call the Drive v3 API
# supose that 213fkrjbk324fnvbknfd is the folder id
query = "'213fkrjbk324fnvbknfd' in parents"
response = service.files().list(q=query,spaces='drive',fields='files(id,name,parents)').execute()
for document in response['files']:
#file_id = service.files.list()
request = service.files().get_media(fileId=document['id'])
fh = io.FileIO('filename.extension',mode='wb')
downloader = MediaIoBaseDownload(fh,request)
done = False
while done is False:
status,done = downloader.next_chunk()
print(document['name'])
print ("Download %d%%." % int(status.progress() * 100))
print("-------------------------------------------------------------------------------------")
if __name__ == '__main__':
main()
当我运行此代码时,控制台显示下载 100% 字符串,但我无法在脚本位置和本地存储的其他位置找到文件。
解决方法
下载的数据仍然存储在 RAM 中。这会将数据复制到您的 python 文件所在的文件夹。
while done is False:
[....]
# This is where it downloads the file
fh.seek(0)
with open('your_filename.pdf','wb') as f:
shutil.copyfileobj(fh,f,length=131072)
如果您遇到问题,我找到了这个答案 here。