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

时间:2014-12-28 23:59:23

标签: python python-2.7

我想使用open('file.txt','w')制作和写入新文件。但我想使用程序中的一些字符串给这个文件命名。例如。我有变量s = 'new_file'。我希望这个新文件的名称为new_file.txt

1 个答案:

答案 0 :(得分:0)

通过将变量作为第一个参数传递给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.txtpepper.txtcumin.txt的文件,每个文件都包含给定的句子。