2

In requests library, if you need to execute

curl http://www.example.com/file.xlsx

The command is

response = requests.get('http://www.example.com/file.xlsx')

What If I want to execute the command with -O option?

curl http://www.example.com/file.xlsx -O

How do I achieve that?

2
  • it is not clear whether you need the curl command with O option or the requests equivalent of curl command Commented Feb 11, 2021 at 10:48
  • I want to achieve curl http://www.example.com/file.xlsx -O using python Commented Feb 11, 2021 at 10:50

3 Answers 3

2

There's no explicit "-O" = write to the same filename. You if you need that, you can store the url in a variable and use several ways of getting it. A lazy way is using rpartition('/')[2] on the url string.

The rest of the code to quickly save the result is here:

import requests
from pathlib import Path

response = requests.get('http://www.example.com/file.xlsx')
Path('file.xlsx').write_bytes(response.content)

# or if you want to have the file name extracted use this less readable line
# Path(response.url.rpartition('/')[2]).write_bytes(response.content)
Sign up to request clarification or add additional context in comments.

Comments

2

To achieve the use case of CURL's -O option in Python, you have to write few lines of code like,

import requests
r = requests.get('https://your.url.com/path')

with open('path.txt','w') as fd:
    fd.write(r.text)

1 Comment

Your example only works for text files. To write a binary file (like from the question), you need to open the file with "wb" and write r.content instead of the r.text.
1

I'm not sure requests supports a flag for this purpose. However, you can try doing something like:

from pathlib import Path

p = Path('http://www.example.com/file.xlsx')
r = requests.get(str(p))
Path(p.name).write_bytes(r.content)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.