我正在尝试使用glob.glob(*.txt)
循环浏览目录中的一系列文件,并且每个文件只占一行。我设法让它在一个文件中循环并获得正确的行,但是,迭代在一个文件之后停止,而不是继续遍历目录中的所有文件。我确信这是一个我忽略的小细节,但我无法弄清楚它是什么。完整的代码是:
import glob
def compile():
for filename in glob.glob('*.txt'):
outfile = 'Stats_Table.txt'
with open(filename, 'r') as file, open(outfile, 'w') as out:
print('comparison F_calc F_table t_calc t_table p', file = out)
print('_______________________________________________________________________________', file = out)
for i, line in enumerate(file):
if i == 2:
print(filename[:-4],' ', line, file = out)
compile()
我从中获取数据的文件格式为:
F_calc F_table t_calc t_table p
______________________________________________________________
29.63872 9.27663 10.27471 2.25956 0.00147
我在一次迭代后获得的最终结果是:
comparison F_calc F_table t_calc t_table p
______________________________________________________________________________
swa-teccu1 58.74018 9.27663 32.2219 2.30274 5e-05
编辑:工作文件,对任何感兴趣的人如下:
import glob
def compile():
outfile = 'Stats_Table.txt'
with open(outfile, 'w') as out:
print('comparison F_calc F_table t_calc t_table p', file = out)
print('_______________________________________________________________________________', file = out)
for filename in glob.glob('*.txt'):
with open(filename, 'r') as file:
for i, line in enumerate(file):
if i == 2:
print(filename[:-4],' ', line.strip(), file = out)
compile()