Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么Google Drive API在通过Python上传文件时会损坏我的文件扩展名?_Python_Excel_Google Api_Google Drive Api - Fatal编程技术网

为什么Google Drive API在通过Python上传文件时会损坏我的文件扩展名?

为什么Google Drive API在通过Python上传文件时会损坏我的文件扩展名?,python,excel,google-api,google-drive-api,Python,Excel,Google Api,Google Drive Api,我创建了一个Python脚本,它从我的计算机上的文件夹中提取.xlsx格式的文件,并将文件上传到我的Google驱动器中的特定文件夹。这是使用Python中的pydrive包。脚本运行时没有问题,文件按预期上载。但是,由于某些原因,当下载并重新打开上载的Google Drive文件时,Excel会显示以下错误消息: Excel无法打开文件…因为文件格式或文件扩展名无效。验证文件是否已损坏,以及文件扩展名是否与文件格式匹配 当我直接在计算机上打开文件时,它可以正常打开,没有任何问题。当我手动将文件

我创建了一个Python脚本,它从我的计算机上的文件夹中提取.xlsx格式的文件,并将文件上传到我的Google驱动器中的特定文件夹。这是使用Python中的pydrive包。脚本运行时没有问题,文件按预期上载。但是,由于某些原因,当下载并重新打开上载的Google Drive文件时,Excel会显示以下错误消息:

Excel无法打开文件…因为文件格式或文件扩展名无效。验证文件是否已损坏,以及文件扩展名是否与文件格式匹配

当我直接在计算机上打开文件时,它可以正常打开,没有任何问题。当我手动将文件拖放/上传到Google Drive文件夹,然后重新下载文件时,它会毫无问题地打开。转换似乎来自我的Python脚本(见下文)

这里有人能帮忙吗?我一直在尝试不同的事情,我一直得到相同的结果。如有必要,我可以提供更多信息

已更新以添加完整的Python脚本:

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

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)

#Google Drive Folder ID
fid = '[FOLDER ID PLACEHOLDER]'

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

starting_folder = '[FOLDER PLACEHOLDER]'

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

destination_folder = starting_folder + "/" + today

#Change directory to the folder where the bulk bid tools are stored
os.chdir("[FOLDER PLACEHOLDER]")

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

print("All files have been uploaded")


实际上,您并没有将文件的信息传递给请求。也就是说,您并没有真正将此文件的实际“字节”上载到驱动器。只是在确定的文件夹中创建一个同名的空驱动器文件

如果您查看,您可以看到在调用
CreateFile
之后,他们使用的

从文档中复制您可以看到如下示例:

file2=drive.CreateFile()
file2.SetContentFile('hello.png')#这一行需要添加到代码中
#使用计算机中的文件名
file2.Upload()文件
#之后还要检查mimetype,以检查文件是否已正确上载
打印('已创建文件%s,mimeType为%s'(文件2['title']),
文件2['mimeType']))
#使用mimeType image/png创建了hello.png文件

另外,从评论中可以看出,您仍然在运行python2代码。考虑到Python2已经“死了”,不会有更多的安全更新,也不会有开发/支持。您真的应该考虑更改,因为许多包和模块也正在(或将开始)放弃对python 2的支持


有关此问题的详细信息,请参阅。

是否有原因尝试打开该文件进行阅读?打开文件后,您根本不使用
f
。另外,您正在使用
驱动器
-您能否共享软件包的特定安装版本,并完成代码以包含您认为使其正常工作所需的导入?更新了我帖子中的代码以帮助解决该问题
f
用于获取基本文件名。我安装了pydrive的最新版本。如果有帮助的话,我仍然在使用Python2.7。在这个时候编写新的Python2.7代码可能是一个非常糟糕的主意,除非你有某种外部依赖,这是绝对需要的。而不是打开一个文件来获取它的名字,简单地考虑使用<代码>路径>代码> > <代码> PATLIB < /代码>或适当的调用>代码> OS.Posith函数-你不需要打开一个文件来获取它的名字,同时它可能会影响你对文件的处理。谢谢!!!!!这是正确的答案。我错过了需要设置contentfile的代码行,这就是为什么我的文件中没有任何数据。我真的很感谢你的帮助。首先要问一个成功的问题!