将python代码移植到python 3的问题

时间:2013-06-09 23:46:51

标签: python

任何人都可以在python 3中告诉我相当于下面的代码吗?

file_list = range(1, 20)

for x in file_list:
    exec "f_%s = open(file_path + '/%s.txt', 'w')" % (x, x)

我需要打开19个文件。所有都具有与之关联的变量名称。

4 个答案:

答案 0 :(得分:5)

我建议您使用字典而不是使用exec创建不同的变量名称:

f = {x:open('{}/{}.txt'.format(file_path, x), 'w') for x in range(1, 20)}

答案 1 :(得分:2)

Python 3中的

exec is now a function。您应该使用.format()

exec("f_{0} = open(file_path + '/{0}.txt', 'w')".format(x))

此外,没有理由使用它。正如其他人所指出的那样,一个简单的字典应该可以工作:

d = {}
for i in range(1,20):
    d['f_'+str(i)] = open(file_path + '/{}.txt'.format(i), 'w')

答案 2 :(得分:2)

我可以推荐一款不需要exec的更好的代码吗?

import os
file_list = range(1, 20)

f = {}
for x in file_list:
    f[x] = open(os.path.join(file_path, '{0}.txt'.format(x)), 'w')

答案 3 :(得分:0)

这是打开文件列表的坏方法。使用清单:

import os
file_path = '.'
files = [open(os.path.join(file_path,'{}.txt'.format(i)),'w') for i in range(1,20)]