How to Read Numbers from File in Python

How to read numbers from file in Python?

Assuming you don't have extraneous whitespace:

with open('file') as f:
w, h = [int(x) for x in next(f).split()] # read first line
array = []
for line in f: # read rest of lines
array.append([int(x) for x in line.split()])

You could condense the last for loop into a nested list comprehension:

with open('file') as f:
w, h = [int(x) for x in next(f).split()]
array = [[int(x) for x in line.split()] for line in f]

How to read numbers from a mixed txt file in python

If you know how to use python regex module you can do that:

import re

if __name__ == '__main__':

with open(TEST_FILE, 'r') as file_1:
for line in file_1.readlines():

if re.match(r'(\d+\s){4}', line):
line = line.strip() # remove \n character
print(line) # just lines with four numbers are printed

The result for you file example is:

567 45 32 468
974 35 3578 4467
325 765 355 5466

How do I read numbers from a text file in python?

In essence you need to do the following:

  1. You need a variable in which you will store the total sum of the numbers in your file
  2. You should use open in order to open the file in a with statement, I am assuming your file is called file.txt.
  3. You need to iterate a file object line by line.
  4. You need to convert the current line in a list of strings in which each element string represents a number. It is assumed all the elements in the file are integers and that they are separated by spaces.
  5. You need to convert that list of strings into a list of integers
  6. You need to sum the elements in the list of step 5. and add the result to total
total = 0 # variable to store total sum

with open('file.txt') as file_object: # open file in a with statement
for line in file_object: # iterate line by line
numbers = [int(e) for e in line.split()] # split line and convert string elements into int
total += sum(numbers) # store sum of current line

print(f"the sum of these numbers is {total}")

Reading numbers from a text file in python

You haven't specified what exactly you meant by matrix, so here is a solution that will turn your text file into a 2d list, making each number individually accessible.

It checks that the first item in a given row is a number, and that there are 4 items in the row, in which case it will append that line as 4 separate numbers to the 2d list mat. If you want to access any number in mat, you can use mat[i][j].

with open("test.txt") as f:
content = f.readlines()

content = [x.strip() for x in content]
mat = []

for line in content:
s = line.split(' ')
if s[0].isdigit() and len(s) == 4:
mat.append(s)

How to read numbers in text file as numbers in to list?

just cast your strings into integers:

g_colour_list.append(int(line.strip('\n')))

Only read the numbers in file

You can use .isnumeric():

with open("list.txt") as input_file:
words = input_file.readline().split()
result = [int(word) for word in words if word.isnumeric()]
print(result)

This outputs:

[5, 1, 0, 0, 2, 1]

Python extract numbers from text file and total

Filter all the price, append them in a list, then sum the list,like:

with open("cart.txt", "r") as text_file:
all_the_price = [float(line.split(", ")[2]) for line in text_file]
total = sum(all_the_price)
print(total)

Adding to an integer stored in a text file in python?

If you have an integer in the first line, first column, you can use this method which will also keep any other data in the file (it is possible to also have the integer somewhere else but that either makes this method a bit more complicated or have to use a different method):

def add_one():
with open('myfile.txt', 'r+') as file:
integer = int(file.readline())
print(integer)
# sets the file pointer? at the first byte
# so that the write method will overwrite the first bytes of data
file.seek(0)
file.write(str(integer + 1))


add_one()


Related Topics



Leave a reply



Submit