【问题标题】:How to get number only values from a specific row from different text file如何从不同文本文件的特定行中获取仅数字值
【发布时间】:2020-07-09 20:59:34
【问题描述】:

我试图仅从 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()

【问题讨论】:

  • 请编辑您的问题并将示例输入和预期输出 + 到目前为止您尝试了什么。
  • 嗨 Andrej,我无法在此处附加文件,我已经编辑了问题。
  • 您的预期输出是什么?例如文件output.txt 包含1 2 3 4 5 6 7 8 9 10 ?
  • 好的。知道了。在第 69 行我有这样的:numOfDonors:2097, numOfAcceptors:1095, numOfPairs:511,每个文本文件。我只想要每个文本文件中的这些数字并将它们组合在一起作为输出文件。

标签: python python-3.x text opentext read-text


【解决方案1】:

你可以试试这个脚本,它会从所有文件中提取第 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)

【讨论】:

  • 嗨 Andrej,我已经尝试过这个脚本,但它显示错误“FileNotFoundError: [Errno 2] No such file or directory: 's0101-ca.tiff.txt'。
  • @ArpanBhattacharya 试试 with open(os.path.join(path, filename), 'r') as f_in: 我更新了我的答案。
  • 嗨 Andrej,将“文件名”更改为“文件”后,程序正在运行,但我没有得到任何输出文件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多