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
#6
@deanhystad I often copy stuff from you experts here and try it out at home. It's a good way to learn.

I made a text file with some text. Added some numbers on each line, then copied all the numbers from above in as well.

But when I try your code, it returns an empty list. Obviously, I'm doing something wrong, but I can't see what. Could you help?

Quote:>>> for filename in input_files:
numbers[filename] = get_numberes_from_file(filename)


[]

import json
import re

path2text = '/home/pedro/temp/'
myfile = 'test_number_finder.txt'
 
integer_pattern = re.compile("[+-]?[0-9]+")
 
def get_numberes_from_file(filename):
    numbers = []
    with open(path2text + 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_number_finder.txt']
numbers = {}
for filename in input_files:
    numbers[filename] = get_numberes_from_file(filename)
Reply


Messages In This Thread
RE: read a text file, find all integers, append to list - by Pedroski55 - Aug-07-2022, 11:24 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Connecting to Remote Server to read contents of a file ChaitanyaSharma 1 161 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,530 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,232 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