我需要在Python 3中使用字符串变量作为文件名

时间:2018-10-23 18:45:04

标签: python python-3.x

with open("name.txt", "w") as f1:
    for line in f:
        f1.write(line)

我需要open("name.txt", "w")才能成为open(variable + ".txt", "w")之类的东西;我是python新手,不胜感激!

感谢所有提供帮助的人,这是我的最终代码:

with open(f'aWord{name}.txt', "w") as f1:                
   for line in f:
       f1.write(line)

1 个答案:

答案 0 :(得分:3)

您可以在python中以多种方式实现

'{}.txt'.format(variable)
'{one}.txt'.format(one=variable)
'%s.txt' % variable
f'{variable}'

那么您将拥有

with open('{}.txt'.format(variable), "w") as f1:
    ...