从github下载txt文件

2024-10-02 12:27:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Github中有一个打开的txt文件,但是,我已经尝试了整个StackOverflow来寻找答案-没有任何帮助:

链接到github: https://github.com/netology-code/py-homework-basic-files/blob/master/3.2.http.requests/DE.txt

最后,我完成了以下内容:

import os.path

cwd=os.getcwd()

import requests
url = 'https://github.com/netology-code/py-homework-basic-files/blob/master/3.2.http.requests/DE.txt'
resp = requests.get(url)

filename='file'
filename = os.path.join(cwd,filename)

但在项目目录中并没有新的文件,而且我收到了一堆我不需要的东西,从请求到“resp”文件,我甚至不知道如何下载这个文件本身的文本。有人能帮忙吗

是的,我刚刚看到了一个与文件的链接,它也可以使用,我收到了我想要的,我可以使用它:

https://raw.githubusercontent.com/netology-code/py-homework-basic-files/master/3.2.http.requests/DE.txt

但是,下载的问题仍然存在


Tags: 文件pyhttpsgithubmastertxtcomhttp
2条回答

实际上,您从未将响应写入文件。您所做的只是将当前工作目录与要写入的文件名连接起来

要在当前目录中写入文件,不需要操作系统模块。Python内置了对文件处理的支持

另外,requests模块get方法返回元数据和文本。您可以在对象的text变量中提取纯文本。(下:res.text

import requests as req

url = “https://github.com/netology-code/py-homework-basic-files/blob/master/3.2.http.requests/DE.txt”
res = req.get(url)

file = open(“filename.txt”, “w”)
file.write(res.text)
file.close()

open(f, m)在当前目录中搜索名为f的文件,并尝试打开该文件以读取”r”或写入”w”。如果模式为写入,而文件不存在,Python将尝试创建它

如果您想了解有关文件I/O的更多信息,我建议您遵循关于w3schools.com的指南

请注意,在代码中,您使用以github开头的链接,而您描述为正常工作的链接则以raw.github开头 使用second,您可以执行以下操作:

import requests
url = 'https://raw.githubusercontent.com/netology-code/py-homework-basic-files/master/3.2.http.requests/DE.txt'
resp = requests.get(url)
with open('file.txt', 'wb') as f:
    f.write(resp.content)

此代码将使用下载的内容在当前工作目录中创建file.txt。请注意,我使用了'wb'模式(写入二进制文件)和resp.content,即bytes。响应对象也有.text,即str,但在这种情况下,由于字符编码可能会出现问题

(在Python 3.7.3+请求2.22.0中测试)

相关问题 更多 >

    热门问题