from google.colab import drive
drive.mount('/content/drive')
我尝试写入以下路径:
path_with_space = '/content/drive/My Drive/foo.txt'
path_without_space = '/content/drive/MyDrive/foo.txt'
with open(path_with_space, 'w') as f:
f.write('bar')
with open(path_without_space, 'w') as f:
f.write('baz')
I将文件写入两个不同的路径:/content/drive/My Drive/
(带有空间)和
/content/drive/MyDrive/
(没有空间)。这两条路径似乎都没有错误,并且
os.path.exists()
确认了两个文件。
if os.path.exists(path_with_space):
print(f'File {path_with_space} exists.')
else:
print(f'File {path_with_space} does not exist.')
if os.path.exists(path_without_space):
print(f'File {path_without_space} exists.')
else:
print(f'File {path_without_space} does not exist.')
# Output:
# File /content/drive/My Drive/foo.txt exists.
# File /content/drive/MyDrive/foo.txt exists.
,但是,当我检查我的Google驱动器时,实际上只保存了一个foo.txt,其内容来自第二个写操作。这种行为令人困惑,因为它表明这两条路径被视为可互换。
如果文件夹确实是指同一文件夹,则可以预期此行为。但是,如果是这样,它如何在引擎盖下工作?如果他们不提及同一文件夹,那么为什么会以这种方式行事?
正如2019年2019 stackoverflowPost
所述,其他用户在COLAB中遇到了“我的驱动器”和“ MyDrive”路径的问题。但这并没有发生在我身上。 在这个问题上,有一个建议逃避空间。它与Google的示例笔记本,外部数据:本地文件,驱动器,床单和云存储
。
MyDrive
我还通过使用外壳命令来测试这些变化的方式研究了逃逸空间的工作方式:
My Drive
我得到了:
# Example from https://colab.research.google.com/notebooks/io.ipynb
with open('/content/drive/My Drive/foo.txt', 'w') as f:
f.write('Hello Google Drive!')
!cat /content/drive/My\ Drive/foo.txt
Escaped space:
Hello Google Drive!
Wrapped path with escaped space:
cat: '/content/drive/My\ Drive/foo.txt': No such file or directory
With space:
cat: /content/drive/My: No such file or directory
cat: Drive/foo.txt: No such file or directory
Wrapped path with space:
Hello Google Drive!
Without space:
Hello Google Drive!
导致的
open()
我注意到with open(path_with_escaped_space, 'w') as f:
f.write('qux')
我记得他们最初支持“我的驱动器”。然后,他们后来添加了MyDrive作为替代名称,以使键入它更轻松而无需引用。他们基本上指的是同一件事。