我有一个循环来连续打开不同的文件和日志数据。 (下面的测试片段)为什么打开所有3个文件并只将数据写入最后一个文件?
for i in range(0, ranks):
current_data_file = open(current_path + 'LOG-rank-%s-die-%s.txt' %(str(i), str(len(rank0_device))), 'w+')
print 'Editing %s' %(current_data_file)
current_data_file.write("Device,")
for j in range(0, len(rank0_device)):
current_data_file.write('5,')
current_data_file.write("\n")
print 'written to %s' %(current_data_file)
current_data_file.close()
Editing <open file 'test_log_data/2015-07-02-10-55-11-3-10/LOG-rank-0-die-10.txt', mode 'w+' at 0x7fae50df4780>
Editing <open file 'test_log_data/2015-07-02-10-55-11-3-10/LOG-rank-1-die-10.txt', mode 'w+' at 0x7fae50df48a0>
Editing <open file 'test_log_data/2015-07-02-10-55-11-3-10/LOG-rank-2-die-10.txt', mode 'w+' at 0x7fae50df4780>
written to <open file 'test_log_data/2015-07-02-10-55-11-3-10/LOG-rank-2-die-10.txt', mode 'w+' at 0x7fae50df4780>
closing <open file 'test_log_data/2015-07-02-10-55-11-3-10/LOG-rank-2-die-10.txt', mode 'w+' at 0x7fae50df4780>
它应该是open-&gt; write ... open-&gt; write..open-&gt; write
答案 0 :(得分:1)
您确定缩进是否正确,并且脚本看起来不像 -
for i in range(0, ranks):
current_data_file = open(current_path + 'LOG-rank-%s-die-%s.txt' %(str(i), str(len(rank0_device))), 'w+')
print 'Editing %s' %(current_data_file)
current_data_file.write("Device,")
for j in range(0, len(rank0_device)):
current_data_file.write('5,')
current_data_file.write("\n")
print 'written to %s' %(current_data_file)
current_data_file.close()
从你的日志看起来,你的脚本看起来像上面那样,python使用缩进来决定块,所以你应该正确地打算使用它们来表明它们在for循环中。
示例 -
for i in range(0, ranks):
current_data_file = open(current_path + 'LOG-rank-%s-die-%s.txt' %(str(i), str(len(rank0_device))), 'w+')
print 'Editing %s' %(current_data_file)
current_data_file.write("Device,")
for j in range(0, len(rank0_device)):
current_data_file.write('5,')
current_data_file.write("\n")
print 'written to %s' %(current_data_file)
current_data_file.close()