0

I'm trying to make a code that downloads a file if it doesn't exist

import requests
from os.path import exists
def downloadfile(url):
    if exists('file.txt')==False:
        local_filename = url.split('/')[-1]
        with requests.get(url, stream=True) as r:
            r.raise_for_status()
            with open(local_filename, 'wb') as f:
                for chunk in r.iter_content(chunk_size=8192):
                    f.write(chunk)
        return

downloadfile('https://url.to/file.txt')

my folder:

testfolder
    test.py
    file.txt
    ...

in idle

from os.path import exists
exists('file.txt') # True

in test.py, exists() say False how fix it?

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • 1
    Hello, and welcome to StackOverflow! Python looks for the file `file.txt` in the *current folder*, not the folder the script is located. Are you sure that 1) the file exists and 2) `test.py` is running in the directory `testfolder`? – David Jul 31 '22 at 03:00
  • 2
    I bet this is just a problem with you not understanding what *relative* pathnames mean. When you call `exists('file.txt')`, it is testing to see if a file called "file.txt" exists *in the current directory*. A common reason for it to fail is that the current directory is not where you expect it to be. So ... basically ... the `exists` call is looking in the wrong place. – Stephen C Jul 31 '22 at 03:00
  • To find out what the current directory is for the script your are running: `print(os.cwd())`. Note that your IDE (I assume that is what you meant by "idle") may *change* the current working directory to be different to what your command shell says it is. On Linux / MacOS, every process has its own notion of the current directory. Changing it in one process doesn't change it for other processes. – Stephen C Jul 31 '22 at 03:04

1 Answers1

0

If it reads false, it's probably looking in the wrong place. Use the following to see where the code is looking in (file directory):

import os

print(os.getcwd())

Then you can either put the file you're looking for in that directory or change the code to the file directory which the file is currently in.

DialFrost
  • 1,610
  • 1
  • 8
  • 28