【问题标题】:dynamic name for a file in PythonPython中文件的动态名称
【发布时间】:2019-12-05 21:43:39
【问题描述】:

我有一个 subject_id,它是一个动态数字。例如,它可能等于 60。我手动定义了一些文件名,如下所示: x_file = "50.txt" x_csv_file = "50.csv" 数字 (50) 可以是 1 或其他任何数字。有什么方法可以让我定义一次subject_id=50,然后将这些名称用作x_file = "subject_id.txt"x_csv_file = "subject_id.csv"?。 感谢您的帮助

【问题讨论】:

  • 您可能想要保存subject_id='50',然后执行x_file=subject_id + '.txt'x_csv_file=subject_id + '.csv: 两个字符串之间的+ 充当连接运算符,因此将字符串粘贴在一起以生成您的期望的输出
  • 感谢您的帮助。但它给了我以下错误:TypeError: unsupported operand type(s) for +: 'int' and 'str
  • 你可能错过了数字周围的引号
  • @LukasThaler 谢谢卢卡斯。你说的对!感谢您的帮助

标签: python pandas numpy dynamic filenames


【解决方案1】:

您可能想为此定义一个简单的函数

def file_name(subject_id):
    x_file = '{}.txt'.format(subject_id)
    x_csv_file = '{}.csv'.format(subject_id)
    return x_file, x_csv_file

【讨论】:

  • 魅力十足!
  • 你也可以用 Lukas 的解决方案做x_csv_file = str(subject_id) + '.csv' :)
  • 为什么不使用 f-strings?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-30
  • 1970-01-01
  • 1970-01-01
  • 2014-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多