将用户定义的变量复制到字符串中

Copy a user defined variable into string

我正在尝试复制用户定义的变量,例如:

print('Enter date required e.g. 2021-08-14 : ')
inputdate = input()

变成这样的字符串:

dest_dir = "N:/RAW Ingest Backup/2021/2021-08/inputdate".

如何将 inputdate 变量连接到 dest_dir 定义中?

你需要这样的东西吗?

input_date = input("Enter a date: ")
destination_dir = rf"N:/RAW Ingest Backup/2021/2021-08/{input_date}"
print(f"Location is : {destination_dir}")

如果我错了我真的不明白你的问题。

假设您的输入始终采用“%Y-%m-%d”格式,您可以将 str.split() 与 f 字符串一起使用:

print('Enter date required e.g. 2021-08-14 : ')
inputdate = input()
year,month,day = inputdate.split("-")

dest_dir = f"N:/RAW Ingest Backup/{year}/{year}-{month}/{inputdate}"
'N:/RAW Ingest Backup/2021/2021-08/2021-08-14'

>>> dest_dir #with inputdate '2021-08-14'
'N:/RAW Ingest Backup/2021/2021-08/2021-08-14'

编辑

如果要验证用户输入的日期是否有效,请使用:

from datetime import datetime
print('Enter date required e.g. 2021-08-14 : ')
inputdate = input()
date = datetime.strptime(inputdate, "%Y-%m-%d")
dest_dir = f"N:/RAW Ingest Backup/{date.year}/{date.strftime('%Y-%m')}/{inputdate}"

>>> dest_dir #with input 2021-08-14
'N:/RAW Ingest Backup/2021/2021-08/2021-08-14'
#Thanks to you all for your advice. This is the solution to my problem
#works like a dream:

import shutil
import os

print('Enter date required e.g. 2021-08-14 : ')
inputdate = input()
year,month,day = inputdate.split("-")

# path to source directory.
src_dir = f"L:/Master_Images/{year}/{year}-{month}/{inputdate}"
print(f"Source Location is : {src_dir}")

# path to destination directory. **** Destination directory should not exist .
dest_dir = f"N:/RAW Ingest Backup/{year}/{year}-{month}/{inputdate}"
print(f"Destination Location is : {dest_dir}")

print('Collating all files from Source Directory')
files = os.listdir(src_dir)

print('Copying all files to Destination Directory')
# copy entire contents to the destination directory
shutil.copytree(src_dir, dest_dir)