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
#8
(Aug-07-2022, 09:45 PM)deanhystad Wrote: I don't understand what you mean by "save the dictionary in a text file"? What file format do you want to use? What are the keys in the dictionary?

This code saves the dictionary as a json format file. For keys I use the filename of the input file.
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:
            if line.startswith("*Nset"):
                break
        for line in file:
            if line.startswith("*Text"):
                break
            numbers += map(int, re.findall(integer_pattern, line))
    print(numbers)
    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)
I don't understand what you were doing with the short name output files.

Thank you very much :), it's exactly what I needed to make my program work. you save my day :)
Reply


Messages In This Thread
RE: read a text file, find all integers, append to list - by oldtrafford - Aug-08-2022, 07:36 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Connecting to Remote Server to read contents of a file ChaitanyaSharma 1 168 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 559 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,535 Nov-09-2023, 10:56 AM
Last Post: mg24
  How to read module/class from list of strings? popular_dog 1 500 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,169 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,158 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