【问题标题】:Python Variable with Asterisk带星号的 Python 变量
【发布时间】:2022-11-16 13:42:10
【问题描述】:

我需要创建一个带星号的变量。

originalFilePath = "/home/user/reports/file_name_xxxx.pdf"

file_name 每天都会用时间戳替换,例如 - file_name_20221116.pdf。如何在变量中传递“*” - 星号?

所以代码看起来像 -

originalFilePath = "/home/user/reports/file_name_*.pdf"

任何帮助,将不胜感激。

【问题讨论】:

    标签: python


    【解决方案1】:

    如果你想这样创作,

    originalFilePath = "/home/user/reports/file_name_xxxx.pdf"
    

    你必须像下面这样传递你的论点。

    abc = "xxxx"  #abc is a variable name
    originalFilePath = f"/home/user/reports/file_name_{abc}.pdf"
    

    【讨论】:

      【解决方案2】:

      F弦呢?

      import datetime
      timestamp = datetime.datetime.now().date()
      originalFilePath = f"/home/user/reports/file_name_{timestamp}.pdf"
      

      您还可以在这样的目录中搜索文件:

      import os
      from os import listdir
      from os.path import isfile, join
      
      current_path = os.path.dirname(os.path.dirname(__file__))
      onlyfiles = [f for f in listdir(current_path) if isfile(join(current_path, f))][0]
      originalFilePath = f"/home/user/reports/{onlyfiles}"
      

      【讨论】:

      • 这有帮助。将来,可能需要一些随机字符。这就是为什么我希望选择“*”。
      • 如果存在多个文件,您如何确保获得正确的文件?不要忘记投票或接受答案:)
      • 目录中一次只有一个文件。
      • 再次检查我的答案,我添加了另一种方式
      猜你喜欢
      • 2015-06-25
      • 1970-01-01
      • 2021-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-01
      • 2021-11-01
      相关资源
      最近更新 更多