0

我试图从 10 个不同的文本文件中仅从特定行中获取数字。作为输出,我希望将这些数字附加为列表。我是一个新的学习者。我会很感激你的帮助。试过这个但不工作

import os
import sys,re
line_number=69 
path = r'C:\Users\arpan\OneDrive\Desktop\New folder' 

for filename in os.listdir(path):
   with open(os.path.join(path, filename), 'r') as f: 
       #print (filename)
       file = open(filename)
       all_lines_variable = file.readlines()
       sys.stdout = open("output", "a")    #print output file
       print(filename, all_lines_variable[line_number])
sys.stdout.close()
4

1 回答 1

0

你可以试试这个脚本,它将从所有文件中提取第 69 行,然后将其附加到output.txt文件中:

import os
import re

line_number=69
path = r'C:\Users\arpan\OneDrive\Desktop\New folder'

with open('output.txt', 'w') as f_out:
    for file in os.listdir(path):
        with open(os.path.join(path, file), 'r') as f_in:
            lines = f_in.readlines()
            print(' '.join(re.findall(r'\d+', lines[line_number])), file=f_out)
于 2020-07-09T22:30:54.980 回答