如何在google Collab中打开文本文件

时间:2018-04-30 09:20:44

标签: jupyter-notebook python-3.5 google-colaboratory

我最近使用谷歌协作juypter笔记本。上传文本文件后,无法在python 3中使用open函数打开文件。

from google.colab import files
import io

uploaded = files.upload()

for fn in uploaded.keys():
  print('User uploaded file "{name}" with length {length} bytes'.format(
      name=fn, length=len(uploaded[fn])))
data_path = io.StringIO(uploaded['fra.txt'].decode('utf-8'))
with open(data_path, 'rb') as f:
    lines = f.read().split('\n')

但是它给出了这个错误:TypeError:期望str,bytes或os.PathLike对象,而不是_io.StringIO

如何在google collab juypter notebook中打开文本文件?

3 个答案:

答案 0 :(得分:1)

更改为

data_path = 'fra.txt'

应该工作。

答案 1 :(得分:0)

_io.StringIO引用StringIO对象(内存中文件流)。 "对于字符串,StringIO可以像在文本模式下打开的文件一样使用。"

问题是该文件已经打开,您可以将它作为StringIO缓冲区使用。我想你想对StringIO对象(data_path)做readlines()。

您还可以在对象上调用getvalue()并获取整个缓冲区的str。

https://docs.python.org/3/library/io.html#io.StringIO

见我的例子;我从你的代码开始...

https://colab.research.google.com/drive/1Vbh13FVm02HMXeHXx-Zko1pFpqyp7bwI

答案 2 :(得分:0)

这样做

1