我在将变量放入路径时遇到问题

时间:2018-11-12 09:56:31

标签: python linux variables

可以在python / linux中将变量放入路径

例如:

>>>counter = 0;

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

我这样做时遇到语法错误。

3 个答案:

答案 0 :(得分:2)

如果您使用的是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'))

答案 1 :(得分:1)

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

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

答案 2 :(得分:1)

您需要string concatenation

>>>counter = 0;

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