0

I have script that downloads a file from a site and is saved into my downloads folder. I want to change the name of that file and move it to new folder. I already have code that generates the new filename, but i'm not sure how to take it into effect. This is what I have:

newfile_name='generated from user input'
os.listdir("C:\Users\qzh14\Downloads")
os.rename("originalfile","newfile_name")
shutil.move("CurrentFolder", "NewFolder")
EagleTamer
  • 47
  • 8

1 Answers1

1

I'm not sure if that's your full code, but I would use the rename method of os.

import os
mypath = "mydir/myfolder"
new_name = input("What's the new name? ")
# assuming you only have one file in your dir
old_name = os.listdir(mypath)
#create new folder in current dir
new_path = mypath + "newfolder"
# not sure you created your new folder, so I'm using a method to create one
os.renames(old_name, (new_path + "/" + new_name))

Tell me if I've missed anything. I'm relatively new to Python but I've been doing similar work. Hope this helps :)

Update: Searching for a file If you want to select a file from the available files, you can look at which files are there an manually enter the file you want. Something like this:

in_folder = os.listdir(mypath)
print(in_folder)
old_name = input("Which of these files? ")
thleo
  • 742
  • 2
  • 8
  • 21
  • I apologize for such a late response, but since it's in my download folder i have different files in there. Is there a way to search for a specific file?I also think I may be formatting the my path incorrectly. mypath= "mydir\C:\Users\qzh14\Downloads" It gives me a unicode error. – EagleTamer Nov 11 '16 at 13:24
  • Hey, sorry that I missed it in my code as well, but the slashes need to be forward slashes, not backslashes. Python might be looking for a special character if you use backslashes. – thleo Nov 11 '16 at 15:37
  • I have updated my code to reflect the above comment. – thleo Nov 11 '16 at 15:38
  • I changed it to "mydir/C:\Users\qzh14\Downloads" & "mydir/C:/Users/qzh14/Downloads", but it gives me syntax errors :( – EagleTamer Nov 11 '16 at 15:58
  • All the strings in my code are placeholders, except for the fw slash in the os.renames call. Replace the strings with your directories, and remove "mydir/". – thleo Nov 11 '16 at 17:00