1

I have an open txt file in Github, however, I've tried the whole StackOverflow for answers - and there are nothing that could help:

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

At the end, I've completed with:

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)

But there is no new file in directory of project, as well as I'm recieving a bunch of stuff that I don't need from asking to "resp" file, and I don't even know how to download the text of this file itself. Could somebody help, please?

Yes, I've just saw a link with file, it also could be use and I recieve exatcly what I want and I can use it:

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

But, the problem of downloading still exists.

Fedor Peplin
  • 149
  • 1
  • 8
  • @Joe - no, unfortunately, it doesn't help. There is a complete empty code as result (as well if I'm trying to "print" variables in steps inside, and there is no creation of file at the end. – Fedor Peplin Apr 16 '20 at 12:14

2 Answers2

3

You never actually wrote the response to a file. All you did was concatenate the current working directory with the filename you wanted to write to.

To write a file in the current directory, you don’t need the OS module. Python has built-in support for file handling.

Also, the requests module get method returns metadata as well as text. You can extract the plain text in the object’s text variable. (Below: 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) searches the current directory for a file with name f and attempts to open it for reading ”r” or writing ”w”. If the mode is write and the file does not exist, Python will attempt to create it.

If you want to learn more about file I/O, I suggest following a guide on w3schools.com

2

Note that in code you use link starting with github, whilst link you describe as working properly starts with raw.github Using second you could do:

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)

This code will create file.txt in current working directory with downloaded content. Note that I use 'wb' mode (write binary) and resp.content which is bytes. Response object has also .text which is str, but problems might arise due to character encoding in this case.

(tested in Python 3.7.3 + requests 2.22.0)

Daweo
  • 31,313
  • 3
  • 12
  • 25