Python 如何命名新文件(字符串连接)?

Python 如何命名新文件(字符串连接)?,python,python-2.7,Python,Python 2.7,我想使用open('file.txt','w')创建并写入新文件。但我想用程序中的字符串来命名这个文件。例如,我有一个变量s='new\u file'。我希望这个新文件的名称为new_file.txt只需将变量作为第一个参数传递给open函数即可创建文件的路径: files_to_create = ['salt', 'pepper', 'cumin'] for i in files_to_create: with open('{0}.txt'.format(i), 'w') as fh:

我想使用
open('file.txt','w')
创建并写入新文件。但我想用程序中的字符串来命名这个文件。例如,我有一个变量
s='new\u file'
。我希望这个新文件的名称为
new_file.txt

只需将变量作为第一个参数传递给
open
函数即可创建文件的路径:

files_to_create = ['salt', 'pepper', 'cumin']
for i in files_to_create:
    with open('{0}.txt'.format(i), 'w') as fh:
        fh.write('this is the file for {0}\n'.format(i))
        fh.close()

上面创建了名为
salt.txt
pepper.txt
cumin.txt
的文件,每个文件中都有给定的句子。

变量
s
的内容必须来自用户输入还是其他内容?不,不。我进行循环,并希望使用另一个文件中的一些名称来创建不同的文件