【问题标题】:Copy a user defined variable into string将用户定义的变量复制到字符串中
【发布时间】:2021-08-16 14:01:48
【问题描述】:

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

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

变成这样的字符串:

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

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

【问题讨论】:

  • 您可以使用fstringpathlib
  • 是否要将输入的日期解析为“2021/2021-08”部分?请给出你想要的更完整的例子。 (此外,一般来说,我们可以看出任何涉及input() 的问题通常都是家庭作业 ;-) -- 这很好,但特别是在这些情况下,告诉我们你尝试了什么会很有用。)
  • 如果我输入了2021-09-01,你希望结果是'n:/RAW Ingest Backup/2021/2021-09/2021-09-01'吗?
  • 这正是我需要的 chepner

标签: python python-3.6


【解决方案1】:

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

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'

【讨论】:

  • split 只能验证词法结构;它无法验证您输入的日期是否有效。使用datetime.strptime 来做这两件事。
  • @chepner - 当然,如果 OP 想要验证输入!
  • 这实际上是给定的。我说的不只是意外地创建了 2021 年 9 月 31 日这样的日期。我说的是year, month, day = "foo-bar-baz".split("-") 之类的东西。
  • 此解决方案运行良好:“假设您的输入始终采用“%Y-%m-%d”格式,您可以将 str.split() 与 f-strings 一起使用:”
  • 谢谢大家。这让我把头发扯掉了。非常非常感谢。
【解决方案2】:

你需要这样的东西吗?

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

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

【讨论】:

    【解决方案3】:
    #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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-28
      • 2016-05-17
      • 2013-09-03
      • 2021-09-19
      • 2021-02-24
      • 2011-10-28
      相关资源
      最近更新 更多