简体   繁体   中英

Saving a directory with a variable name

Pn = input("Give the name of the Project.")

import shutil as sl
sl.copytree(r"C:\Users\Desktop\Automate\Template\C", r"C:\User\Desktop\{Pn}")

What I want to do is save a copy of directory in specific location with user defined name. This just saves it with {Pn} as its name.

Use str.format

Ex:

Pn = input("Give the name of the Project.")

import shutil as sl
sl.copytree(r"C:\Users\Desktop\Automate\Template\C", r"C:\User\Desktop\{Pn}".format(Pn=Pn ))

Even though Rakesh's answer is perfectly fine, if you're using Python >= 3.6, you can also use f-strings for shorter syntax (note the added f before the second string):

Pn = input("Give the name of the Project.")

import shutil as sl
sl.copytree(r"C:\Users\Desktop\Automate\Template\C", rf"C:\User\Desktop\{Pn}")

A couple more things to note:

  • PEP-8 suggests lowercase_with_underscore naming for variables, methods and functions (eg Pn should be pn )
  • It is idiomatic to Python that variable names read as English rather than, obscured, low-level, shortened names (eg pn should be project_name ) - see The Zen of Python for more such "philosophical" principles
  • It is generally a good idea to have imports right on top of your program, since you can easily check out its dependencies and fail-fast on ImportError (see this answer for more details)

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