【问题标题】:How to read .txt files from github into Google colab如何将 .txt 文件从 github 读取到 Google colab
【发布时间】:2020-08-26 14:25:48
【问题描述】:

我在 github 中有一个包含文本文件的文件夹,当我尝试在 Google colab 中阅读以下代码时出现错误

FileNotFoundError: [Errno 2] 没有这样的文件或目录: 'https://github.com/Jainu-s/urldata/tree/master/al?raw=true'

loc = 'https://github.com/Jainu-s/urldata/tree/master/al?raw=true'
#uploaded = files.upload()
os.chdir(loc)
filelist = os.listdir()
#print (len((pd.concat([pd.read_csv(item, names=[item[:-4]]) for item in filelist],axis=1))))

data = []
path = loc
files = [f for f in os.listdir(path) if os.path.isfile(f)]
for f in files:
    with open(f,'r') as myfile:
        data.append(myfile.read())


df = pd.DataFrame(data,columns=['Data'])
print (df.shape)

【问题讨论】:

  • 为什么要从 GitHub 读取文本文件?直接下载到本地?
  • github中的每个文件都有一个原始链接,例如对于您的第一个文本文件:raw.githubusercontent.com/Jainu-s/urldata/master/al/…,您可以修改链接的最后一部分并尝试读取文件。
  • 我添加到原始链接但我仍然无法阅读,因为它会引发错误

标签: python-3.x github google-colaboratory


【解决方案1】:
import base64
import requests

master = "https://raw.githubusercontent.com/Jainu-s/urldata/master/al/abescoldbeer.com.txt"
req = requests.get(master)
req = req.text
print(req)

通过这种方式,您可以使用修改主字符串的 for 循环读取所有文件

https://stackoverflow.com/a/38497199/10077354你可以参考这个链接了解阅读github文件。

【讨论】:

【解决方案2】:

您可以先将该目录中的所有文件下载到 Colab:

!npx degit Jainu-s/urldata/al -f

然后,您可以像本地文件一样循环它。

【讨论】:

  • 工作得很好,谢谢,这段代码属于哪种编程语言
  • degit 是用 JavaScript 编写的。
【解决方案3】:

即使@korakot 的回复是有效的,作为替代解决方案:

!git clone https://github.com/Jainu-s/urldata.git
path = '/content/urldata/al'

%cd urldata #go to the directory where git clone says *Cloning into*

for subdir, dirs, files in os.walk(path):
  print(files)

【讨论】:

    猜你喜欢
    • 2021-09-27
    • 1970-01-01
    • 2023-02-03
    • 2022-01-18
    • 2020-02-02
    • 2022-01-19
    • 2020-09-17
    • 1970-01-01
    • 2021-02-24
    相关资源
    最近更新 更多