【问题标题】:I have some issue putting variable into the path [duplicate]我在将变量放入路径时遇到了一些问题[重复]
【发布时间】:2019-04-15 00:39:05
【问题描述】:

可以在python/linux的路径中放一个变量

例如:

>>>counter = 0;

>>>image = ClImage(file_obj=open('/home/user/image'counter'.jpeg', 'rb'))

当我这样做时出现语法错误。

【问题讨论】:

  • documentation 在这里可能会有所帮助
  • @Castelo 如果这里的答案对您有所帮助,那么 SO 的标准做法是接受它。请接受对您最有帮助的答案。

标签: python linux variables


【解决方案1】:

如果您使用的是 python 3.6+,则可以使用 f-string

这是最有效的方法。

counter = 0
filepath = f"/home/user/image{counter}.jpeg"
image = ClImage(file_obj=open(filepath, 'rb'))

否则第二好的是使用.format() 函数:

counter = 0
filepath = "/home/user/image{0}.jpeg".format(counter)
image = ClImage(file_obj=open(filepath, 'rb'))

【讨论】:

    【解决方案2】:

    可以使用 Python 的.format() 方法:

    counter = 0
    filepath = '/home/user/image{0}.jpeg'.format(counter)
    image = ClImage(file_obj=open(filepath, 'rb'))
    

    【讨论】:

      【解决方案3】:

      你需要string concatenation

      >>>counter = 0;
      
      >>>image = ClImage(file_obj=open('/home/user/image' + str(counter) + '.jpeg', 'rb'))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-12
        • 1970-01-01
        • 1970-01-01
        • 2019-02-15
        • 1970-01-01
        相关资源
        最近更新 更多