Python Forum
read a text file, find all integers, append to list
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
read a text file, find all integers, append to list
#7
The file needs to look like the example posted by oldtrafford.
Output:
Text .. .. ... .. .. *Nset, nset=PATH, unsorted 13, 721, 722, 723, 724, 725, 726, 727, 728, 729, 730, 731, 732, 733, 734, 735 ... 2559, 2560, 2561, 2562, 2563, 2564, 72 *Text .... ... ... .. Text
I wouldn't be surprised if the starting mark should be Nset, not *Nset, and the ending mark Text, not *Text. Looking at it again I think maybe the numbers start after the Nset line and continue until there is a line that starts with text. Maybe this is a better fit:
import json
import re
 
integer_pattern = re.compile("[+-]?[0-9]+")
 
def get_numberes_from_file(filename):
    numbers = []
    with open(filename, "r") as file:
        for line in file:
            # Marks the beginning of int data
            if line.startswith("Nset"):
                break
        for line in file:
            # Read lines until encounter line without numbers
            matches = map(int, re.findall(integer_pattern, line))
            if matches:
                numbers += matches
            else:
                break
    return numbers
 
input_files = ["test.txt", "test2.txt", "test3.txt"]
numbers = {}
for filename in input_files:
    numbers[filename] = get_numberes_from_file(filename)
 
with open("output.inp", "w") as file:
    json.dump(numbers, file, indent=4)
Reply


Messages In This Thread
RE: read a text file, find all integers, append to list - by deanhystad - Aug-08-2022, 02:34 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Connecting to Remote Server to read contents of a file ChaitanyaSharma 1 163 May-03-2024, 07:23 AM
Last Post: Pedroski55
  PyYAML read list of int zisco 2 355 Apr-02-2024, 12:36 PM
Last Post: zisco
  append str to list in dataclass flash77 6 556 Mar-14-2024, 06:26 PM
Last Post: flash77
  Recommended way to read/create PDF file? Winfried 3 2,939 Nov-26-2023, 07:51 AM
Last Post: Pedroski55
  python Read each xlsx file and write it into csv with pipe delimiter mg24 4 1,532 Nov-09-2023, 10:56 AM
Last Post: mg24
  How to read module/class from list of strings? popular_dog 1 499 Oct-04-2023, 03:08 PM
Last Post: deanhystad
  No matter what I do I get back "List indices must be integers or slices, not list" Radical 4 1,233 Sep-24-2023, 05:03 AM
Last Post: deanhystad
  Program to find Mode of a list PythonBoy 6 1,168 Sep-12-2023, 09:31 AM
Last Post: PythonBoy
  FileNotFoundError: [WinError 2] The system cannot find the file specified NewBiee 2 1,623 Jul-31-2023, 11:42 AM
Last Post: deanhystad
  read file txt on my pc to telegram bot api Tupa 0 1,157 Jul-06-2023, 01:52 AM
Last Post: Tupa

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020