我想循环一个字典并为字典中的每个键创建一个输出文件,并使用该键作为输出文件的名称.这是我试过的:
for id, pos in PNposD.iteritems():
print id, 'id'
print pos, 'pos'
ofh = open("/home/",id,"_candMuts.txt")
ofh.write("%d\n" % (pos))
Run Code Online (Sandbox Code Playgroud)
这是我尝试打开输入文件的行的错误消息(在第4行):
TypeError: file() takes at most 3 arguments (4 given)
Run Code Online (Sandbox Code Playgroud)
使用str.format.您应该使用write mode(w)打开文件以向文件写入内容.
for id, pos in PNposD.iteritems():
print id, 'id'
print pos, 'pos'
with open("/home/{}_candMuts.txt".format(id), 'w') as ofh:
ofh.write("%d\n" % (pos))
Run Code Online (Sandbox Code Playgroud)