繁体   English   中英

如何通过google驱动器的链接找到文件的类型?

[英]How do I find the type of the file through the link of the google drive?

我的谷歌驱动器中有很多文件。 我想根据它的类型来阅读它 like.txt,.pdf,.doc 等。我可以单独阅读它,但我希望通过使用 if else 或任何其他条件来阅读。

这是 read.txt 文件的代码

file_path=link of google drive    
import urllib.request
response = urllib.request.urlopen(file_path)
html = response.read()
text=html.decode('utf8')
print(text)

这是 read.pdf 文件的代码。

import requests, PyPDF2


url = file_path
response = requests.get(url)
my_raw_data = response.content

with open("my_pdf.pdf", 'wb') as my_data:
    my_data.write(my_raw_data)

open_pdf_file = open("my_pdf.pdf", 'rb')
read_pdf = PyPDF2.PdfFileReader(open_pdf_file)
if read_pdf.isEncrypted:
    read_pdf.decrypt("")
    print(read_pdf.getPage(0).extractText())

else:
    print(read_pdf.getPage(0).extractText())

现在我想给出一个条件,如果文件类型是.txt,那么它将相应地读取,如果文件类型是.pdf,那么它将像这样读取 pdf。

那么,如何通过条件找到文件的类型并在一个代码中读取所有类型的文件呢?

我不是 100% 确定我明白你想做什么。

如果您只想获取特定 mime 类型的文件,则可以使用files.list方法的 q 参数按 mimeType 搜索文件

mimeType='application/vnd.google-apps.document'

像这样的东西

    response = service.files().list(q=f"mimeType = 'application/vnd.google-apps.document'",
                                    fields='nextPageToken, files(id, name)'
).execute()

您也可以使用单个 file.list 请求来执行此操作,然后检测每个文件的 mime 类型。 即返回。

 "files": [
  {
   "kind": "drive#file",
   "id": "1x8-vD-XiXEEA5Spf3qp8x2wltablGF22Lpwup8VtxNY",
   "name": "Experts Activity Dump go/ExpertsActivities",
   "mimeType": "application/vnd.google-apps.spreadsheet"
  },

根据返回的文件的 MIME 类型,您可以使用不同的打开方法。 请记住,您将无法以这种方式打开某些文件类型。 任何驱动器类型,如表格和文档,您都需要先导出,然后以您可以处理的格式打开它们。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM