从 google colab 获取 google 驱动器文件 ID

Get google drive file ID from google colab

我正在 google colab 中尝试获取存储在我的 google 驱动器上的文件的文件 ID。

当文件由 google colab 中的函数创建时,我得到一个“local-xxx”形式的文件 ID,而不是实际的文件 ID。当文件手动上传到 google 驱动器时,我得到了正确的 ID。

你能帮我解决这个问题吗?在下面发布我的代码

  image_drive_url = "/content/gdrive/MyDrive/"+file_name+".png"
  image_id = getoutput("xattr -p 'user.drive.id' '%s'" % image_drive_url) 

  print(image_id)

打印:local-702 而不是实际的文件 ID

您可能想查看 this answer 相关问题。

它包含基于以下观察(来自同一线程中的另一个答案)的解决方法的实现:

Note: If you are using this in some type of script that is creating new files/folders and quickly reading the 'user.drive.id' afterwards, be aware that it can take many seconds for the "real" file id to be generated. If you read the value of 'user.drive.id' and it starts with 'local', this means that it has not yet generated an actual file id. In my opinion, the best way to deal with this is to create an asynchronous loop that sleeps between checks, and then returns the file id once it no longer starts with 'local'.

ps。我宁愿 post 这作为评论,但我还没有足够的代表点数 ;-)