为什么Google Drive API(pydrive)无法与shutil.move一起使用?

时间:2020-01-07 22:50:39

标签: python google-api google-drive-api pydrive

我有一个简单的Python脚本,旨在在Windows目录中创建一个文件夹,将一些文件上传到Google云端硬盘,然后将这些文件移至新创建的文件夹并删除原始源文件。

我最初编写脚本时,一切似乎都按计划进行,除了我实际上并没有使用pydrive的SetContentFile命令将数据提交到Google驱动器。添加完后,我注意到shutil.move正在复制文件,但是无法删除原始源文件。我不太清楚为什么,所以我决定将shutil.move移到单独的循环子句中,这似乎解决了我的大部分问题。现在,它正在按预期将我的所有文件复制到新文件夹,但是无法从根文件夹中删除最新的原始源文件。

当我尝试在没有pass的cmd中运行时,它告诉我该文件仍通过其他进程打开。是什么原因导致的?我该如何解决此问题?另外,为什么SetContentFileshutil.move在同一个循环子句中不起作用?任何帮助将不胜感激!

from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
import glob,os,shutil
import datetime, time

os.chdir(os.path.dirname(os.path.abspath(__file__)))

gauth = GoogleAuth()
#gauth.LocalWebserverAuth()

# Try to load saved client credentials
gauth.LoadCredentialsFile("mycreds.txt")
if gauth.credentials is None:
    # Authenticate if they're not there
    gauth.LocalWebserverAuth()
elif gauth.access_token_expired:
    # Refresh them if expired
    gauth.Refresh()
else:
    # Initialize the saved creds
    gauth.Authorize()
# Save the current credentials to a file
gauth.SaveCredentialsFile("mycreds.txt")

drive = GoogleDrive(gauth)

fid = '[FOLDER ID PLACEHOLDER]'

#Check to see if today's folder is created 
date = datetime.date.today()
today = date.strftime('%Y-%m-%d')

starting_folder = '[INSERT STARTING FOLDER]'

if not os.path.exists(starting_folder + "/" + today):
    os.makedirs(starting_folder + "/" + today)

destination_folder = starting_folder + "/" + today

#Change directory to the folder where FILES are stored
os.chdir(INSERT WORKING DIRECTORY)

for file in glob.glob("*.xlsx"):
    try:
        print(file)
        with open(file,"r") as f:
            fn = os.path.basename(f.name)
            fp = os.path.abspath(f.name)
            file_drive = drive.CreateFile({'parents':[{'kind':"drive#parentReference",'id':fid}],'title':fn})
            file_drive.SetContentFile(fp)
            file_drive.Upload()
            print("The file: " + fn + " has been uploaded to Google Drive.")
        #shutil.move(starting_folder + "/" + fn,destination_folder + "/" + fn)
        #    print("The file: " + fn + " has been moved to the folder.")
        f.close()
    except: 
        pass  

for file in glob.glob("*.xlsx"):
    try:
        fn = os.path.basename(file)
        shutil.move(starting_folder + "/" + fn,destination_folder + "/" + fn)
        #    print("The file: " + fn + " has been moved to the folder.")
    except:
        pass
print("All files have been uploaded to Google Drive, and the DRIVE has been updated.")

0 个答案:

没有答案