-1

As said in the title, I'm trying to write a script in python 2.7 that downloads files off of a link and moves it to a specific folder. I'm doing this using raw_input and the os module. But the raw_input for the fileLocation variable isn't registering for the os.system() operation.

I've attempted to instead use two different methods, both use the command line. The first involves using the mv operation in an os.system() operation. The exact code is os.system('mv {} {}'.format(fileName, fileLocation)). The other runs a cd operation through the command line in an attempt to change the download location.

Here is the code:

link = raw_input('Link: ')
fileLocation = raw_input('Input File Location: ')
os.system('cd {}'.format(fileLocation)) 
os.system('curl -O {}'.format(link))
# os.system('mv {} {}'.format(fileName, fileLocation))

The output is clean and shows no errors. What I want to happen is for the file to be downloaded, and then immediately moved to the specified folder using the raw_input operation in fileLocation on line 2, but the file is instead downloaded and kept in the home folder for my user profile.

  • Why do you try with wget instead that has already a -O switch to select the destination folder. – Marco Aug 31 '19 at 14:13
  • @Marco I didn't actually know about that. Although checking it out it won't work for me. I use a Macbook my school gave me. Which means I don't have access to admin, so I can't use brew. – Saul Dickson Aug 31 '19 at 14:19
  • @Goyo Thats the point of the code on line three and the commented out code on line five. – Saul Dickson Aug 31 '19 at 14:21
  • If you are only just learning the basics, you should probably ignore Python 2, and spend your time on the currently recommended and supported version of the language, which is Python 3. – tripleee Aug 31 '19 at 14:36
  • Possible duplicate of https://stackoverflow.com/questions/35277128/why-does-not-os-systemcd-mydir-work-and-we-have-to-use-os-chdirmydir-ins – tripleee Aug 31 '19 at 14:38
  • Possible duplicate of https://stackoverflow.com/questions/44082209/renaming-the-file-downloaded-with-python-requests – tripleee Aug 31 '19 at 14:39

2 Answers2

0

This is happening because command passed in os.system is executed in a subshell. When os.system is returned it loses the change made by cd.

The solution is to either run those command in same os.system call

os.system('cd {}; curl -O {}'.format(fileLocation, link))
Shiplu Mokaddim
  • 56,364
  • 17
  • 141
  • 187
0

Your problem is with this line:

os.system('cd {}'.format(fileLocation)) 

You want to change it to:

os.chdir(fileLocation)

Your original code creates a subprocess to execute the "cd" command but doesn't actually change the directory of your current process. You might want to look at link1 for how to change directory and link2 for an explanation to why os.system('cd <something>') doesn't change directory

blueishpoop
  • 226
  • 1
  • 10