简体   繁体   中英

Copying files from one directory to another python

Hello does anyone know how to copy a file from one directory to another? I have used the "shutil.copy2" it works and gets the copies to the specified output.

Though, my goal is being able to copy files from one directory to another, allowing users to specify which files they want to copy by name. Rather than having to input the dir path every time.

Thought process: Since I specify the file directory. Somehow using a raw_input user can specify which file they want to copy from the specified directory. Posted my code for reference. #Please not BS comments I am new to coding, just trying to learn.

#----------------------------------------------------------------------------------------------------------------#
# These params will be used for specifying which template you want to copy and where to output 
#----------------------------------------------------------------------------------------------------------------#
'''Load file from x directory into current working directory '''

#PullTemplate: Specify which template you want to copy, by directory path

TemplateRepo = ("/home/hadoop/BackupFolders/Munge_Stage_Templates/Templates")

user_input = raw_input("which file do you want to pull:")


#OutputTemplate: Let's you specify where you want to output the copied template.
#Originally set to your current working directory (u".")

OutputTemplate = (u".")


#----------------------------------------------------------------------------------------------------------------#
# STATIC CODE: Do not alter "Just Run!"
#----------------------------------------------------------------------------------------------------------------#
shutil.copy2(TemplateRepo, OutputTemplate)

So a bit of clarification are you trying to have them just enter a filename or are you asking how to get a relative path?

EDIT

Ok so for starters to make you life easier now and in the future use a function will make your life alot easier. Second check out the docs https://docs.python.org/3/library/functions.html#open great resource and most things you want to do it will tell you how. You will have to use the absolute path for saving the file but you can use a relative one for opening it.

The first option for shutil.copy2() should be a file instead of a directory, so you would need to add TemplateRepo and the file name from the input:

TemplateRepo = ("/home/hadoop/BackupFolders/Munge_Stage_Templates/Templates")
user_input = raw_input("which file do you want to pull:")
OutputTemplate = (u".")

InputFile = TemplateRepo + '/' + user_input

shutil.copy2(InputFile, OutputTemplate)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM