【问题标题】:Colab: Printing all lines of a txt file uploadedColab:打印上传的txt文件的所有行
【发布时间】:2021-11-07 12:12:39
【问题描述】:
我正在使用以下方式将文件上传到 colab:
from google.colab import files
uploaded = files.upload()
然后我尝试读取上传文件中的所有行:
for line in uploaded:
print(line)
但我得到的是文件名 text.txt 而不是它的行。
如何正确阅读?
谢谢
【问题讨论】:
标签:
python
jupyter-notebook
google-colaboratory
【解决方案1】:
uploaded 对象是一个字典,其中包含文件名和每个上传文件的内容。
这里有一些代码循环遍历所有上传的文件,每个文件都尝试将内容读入一个行列表,然后打印出来。
from google.colab import files
uploaded = files.upload()
for filename in uploaded.keys(): # get the name of each uploaded file
print(filename)
lines = uploaded[filename].splitlines() # split the contents into lines
for line in lines: # iterate over all lines
print(line.decode('utf-8')) # print the line (it needs to be decoded)