Python: How do I calculate the sum of numbers from a file? - python

How do I calculate the sum of numbers from a .txt file?
Data in file is formatted as:
7
8
14
18
16
8
23
...
I read the data from the file and assign every line value to 'line' vatiable, but I want to get something like: result = 7+8+14+...
f = open('data.txt', 'r') #LOOP AND READ DATA FROM THE FILE
for line in f:
code

This is most compact code I can think of right now:
(updated to handle the n at the end, thanks, #JonClements!)
with open('file.txt', 'r') as fin:
ans = sum(int(line) for line in fin if line.strip().isnumeric())
For the code structure you have, you can also go for this:
f = open('data.txt', 'r')
ans = 0
for line in f:
try:
ans += int(line.strip())
except ValueError:
pass
Edit:
Since the confusion with the 'n' has been cleared, the first example can be as simple as
with open('file.txt', 'r') as fin:
ans = sum(int(line) for line in fin)
Or even this one-liner:
ans = sum(int(line) for line in open('file.txt', 'r'))
But there are certain risks with file handling, so not strongly recommended.

Keep it simple:
with open('data.txt', 'r') as f:
result = sum(map(int, f))
int is mapped over each line from f, then sum() adds up the resulting integers.

file = open("data.txt", "r")
numbers = []
for line in file:
numbers.append(int(line))
print(sum(numbers))
This basically just creates a list of numbers, where each line is a new entry in the list. Then it shows the sum of the list.

A simple solution is, it will take care of the \n at the end of each line as well, based on steven's and AChamp's suggestion
with open("abc.txt","r")as f:
print(sum(int(x) for x in f))

Here is a solution (consider all of the lines are numbers):
def calculate_number_in_file(file_path):
with open(file_path, 'r') as f:
return sum([int(number.strip()) for number in f.readlines()])

with open ('data.txt', 'r') as f:
data = f.readlines()
sum = 0
for line in data:
sum += int(line.strip())
print(sum)

On smartphone...
with open(filepath) as f:
lines = f.readlines()
numbers = [int(line) for line in lines]
print(sum(numbers))

Related

How to read content of txt file the values are comma separated and add it to a list?

I have a file that contains the following content. This is a sample of the file. The fine contains up to 1000 values.
'1022409', '10856967', '11665741'
I need to read the file and create this list ['1022409', '10856967', '11665741']
I'm using the following code:
with open('Pafos.txt', 'r') as f:
parcelIds_list = f.readlines()
print (parcelIds_list[0].split(','))
The value is of parcelIds_list parameter is this list ["'1022409', '10856967', '11665741'"] with only index 0.
Any ideas please?
Follow this code
with open ('Pafos.txt', 'r') as f:
# To split
num = f.readline().split(', ')
# To remove ' and create list
# If u want list of string
num_list = [x.replace('\'', '') for x in num]
Output
['1022409', '10856967', '11665741']
If u want list of int
# If u want list of int
num_list = [int(x.replace('\'', '')) for x in num]
Output
[1022409, 10856967, 11665741]
If u have more than one row in file, you need to add some extra line of code
It is a bit hard to code with the few lines you have given from the text file, but try this :
temp = []
with open('Pafos.txt', 'r') as f:
parcelIds_list = f.readlines()
for j in parcelIDS_list:
temp.extend(j.split(", "))
new_list = [i.strip()[1:-1] for i in temp]
print(new_list)
Let me know if this doesn't work, and what went wrong. I will modify my answer likewise.
I found the solution thanks to this.
with open('Pafos.txt', 'r') as f:
parcelIds_list = f.readlines()
cs_mylist = []
for y in [x.split(',') for x in parcelIds_list]:
for z in y:
cs_mylist.append(z.replace(' ', ''))
Probably there is a cleaner way, but this works:
with open('Pafos.txt', 'r') as f:
parcelIds_list = f.readlines()
line = parcelIds_list[0]
line = line.replace("'", "")
line = line.replace(" ", "")
line = line.split(',')
print(line)

Python how to start reading file after a specific line to a specific line?

I need to make my python code reads emma.txt file after line 32 to line 16266.
fin = open("emma.txt", encoding="UTF-8")
fin.readline()
line= fin.readline()
word = line.strip()
print(word)
fin.close()
fin = open("emma.txt", encoding="UTF-8")
for line in fin:
word = line.strip()
print(word)
The problem is solved with the code below
emma = open("emma.txt", encoding="UTF-8")
lines = emma.readlines()[31:16265]
for line in lines:
print(line.rstrip())
Since storing all lines into memory is not a good idea. you can use islice from itertools module which gives you ability to pick which items you want from an iterator. click
from itertools import islice
with open('your_file.txt') as f:
for line in islice(f, 31, 16266):
# do what you wanna do
It is much more efficient and clean.
Try this:
with open("test.py", "r") as file:
lines = file.readlines()
lines = lines[31:16265]
print(lines)
This saves all the lines as a list and then makes the list the 31st index (32nd line) to the 16265th index (16266th line).
My mistake, my previous answer was incorrect. I have changed it to
lines = lines[21:12265]
Use this to get your answer fast and efficient
start = 31
end = 16266
with open("test.py", "r", encoding="UTF-8") as file:
lines = file.readlines()[start:end]
print(lines)
def read_range_lines(filename, start, end):
if end > start:
return
with open(filename, "r") as file:
count = 0
while count < start - 1:
file.readline()
count += 1
while count < end:
print(file.readline())
count += 1
Using enumerate to track line numbers.
with open('f3.txt') as f:
for line_no, line in enumerate(f):
if 31 <= line_no <= 16265: # assuming line numbered from 0
# Processing of desired lines
print(line)
elif line_no > 1626i5:
# Not required but avoids futher unnecessary file reading
break

I want to write a function which prints a sum

I just started learning Python a few weeks ago and I want to write a function which opens a file, counts and adds up the characters in each line and prints that those equal the total number of characters in the file.
For example, given a file test1.txt:
lineLengths('test1.txt')
The output should be:
15+20+23+24+0=82 (+0 optional)
This is what I have so far:
def lineLengths(filename):
f=open(filename)
lines=f.readlines()
f.close()
answer=[]
for aline in lines:
count=len(aline)
It does what I want it to do, but I don't know how to include all the of numbers added together when I have the function print.
If you only want to print the sum of the length of each line, you can do it like so:
def lineLengths(filename):
with open(filename) as f:
answer = []
for aline in f:
answer.append(len(aline))
print("%s = %s" %("+".join(str(c) for c in answer), sum(answer))
If you however also need to track lengths of all the individual lines, you can append the length for each line in your answer list by using the append method and then print the sum by using sum(answer)
Try this :
f=open(filename)
mylist = f.read().splitlines()
sum([len(i) for i in mylist])
Simple as this:
sum(map(len, open(filename)))
open(filename) returns an iterator that passes through each line, each of which is run through the len function, and the results are summed.
Once you read lines from file you can count sum using:
sum([len(aline) for aline in lines])
Separate you problem in function : a responsible by return total sum of lines and other to format sum of each line.
def read_file(file):
with open(file) as file:
lines = file.readlines()
return lines
def format_line_sum(lines):
lines_in_str = []
for line in lines:
lines_in_str.append(str(line)
return "+".join(str_lines))
def lines_length(file):
lines = read_file(file)
total_sum = 0
for line in lines:
total_sum += len(line)
return format_lines_sum(lines) + "=" + total_sum
And to use:
print(lines_length('file1.txt'))
Assuming your output is literal, something like this should work.
You can use python sum() function when you figure out how to add numbers to the list
def lineLengths(filename):
with open(filename) as f:
line_lengths = [len(l.rstrip()) for l in f]
summ = '+'.join(map(str, line_lengths)) # can only join strings
return sum(line_lengths), summ
total_chars, summ = lineLengths(filename)
print("{} = {}".format(summ, total_chars))
This should have the output you want : x+y+z=a
def lineLengths(filename):
count=[]
with open(filename) as f: #this is an easier way to open/close a file
for line in f:
count.append(len(line))
print('+'.join(str(x) for x in count) + "=" + str(sum(count))

average of .txt file with str and int within it

I'm creating a function that reads a .txt file that contains the following:
Testing.txt:
a 1 34
b 2 25
c 3 23
j 4 80
I need to create a function that reads this file and prints the average of the last 2 digits of each line in the file.
What I have so far is this:
def Stats():
filename = input("Enter a file name: ")
with open(filename) as f:
data = [int(line) for line in f]
print("The average value is ", sum(data)/len(data))
Stats()
Pros:
this function will produce the average of int values within a function.
cons:
It will not work if the file contains str within it.
Question: How can I get my function to work with a file such as the one listed above called (testing.txt)?
I think this is what you are after:
# filename = input("Enter a file name: ")
filename = "input.txt"
def avg_file(filename):
with open(filename, 'r') as f:
data = [int(line.split()[2]) for line in f]
return sum(data)/len(data)
avg = avg_file(filename)
print("The average value is: ", avg)
# The average value is: 40.5
the key is this line.split()[2]. This splits a line based on spaces, and takes 3th value.
You could ignore non-numbers this way:
data = [int(token) for token in f.read().split() if token.isdigit()]
What about something like:
import csv
def mean(lst): return sum(lst) / len(lst)
with open('input.txt') as f:
reader = csv.reader(f, delimiter=' ')
lines = [line for line in reader]
col3 = [int(line[2]) for line in lines]
print(mean(col3)) # 40.5
This just uses the csv module to parse the file lines into rows containing elements. You could accomplish the same thing with something like:
def mean(lst): return sum(lst) / float(len(lst))
with open('input.txt') as f:
lines = [line.split() for line in f]
col3 = [int(line[2]) for line in lines]
print mean(col3) # 40.5
Something like this:
data = [sum(map(int, line.split(' ')[1:])) / 2 for line in f]
Or something more old-school, in case you have unknown mix of string and int values:
data = []
for line in f:
integers = []
for segment in line.split():
try:
integers.append(int(segment))
except ValueError:
pass
data.append(sum(integers) / len(integers))

Change content of multiline file into a list

How can I parse through the following file, and turn each line to an element of a list (there is a whitespace at the beginning of each line) ? Unfortunately I've always sucked at regex :/ So turn this:
32.42.4.120', '32.42.4.127
32.42.5.128', '32.42.5.255
32.42.15.136', '32.42.15.143
32.58.129.0', '32.58.129.7
32.58.131.0', '32.58.131.63
46.7.0.0', '46.7.255.255
into a list :
('32.42.4.120', '32.42.4.127'),
('32.42.5.128', '32.42.5.255'),
('32.42.15.136', '32.42.15.143'),
('32.58.129.0', '32.58.129.7'),
('32.58.131.0', '32.58.131.63'),
How about this? (If I am wrong, at least let me know before down-voting)
>>> x = [tuple(line.strip().split("', '")) for line in open('file')]
>>> x
[('32.42.4.120', '32.42.4.127'), ('32.42.5.128', '32.42.5.255'), ('32.42.15.136', '32.42.15.143'), ('32.58.129.0', '32.58.129.7'), ('32.58.131.0', '32.58.131.63'), ('46.7.0.0', '46.7.255.255')]
no regex needed:
l = []
with open("name_file", "r") as f:
for line in f:
l.append(line.split(", "))
if you want to remove first space and to have tuple you can do:
l = []
with open("name_file", "r") as f:
for line in f:
data = line.split(", ")
l.append((data[0].strip(), data[1].strip()))
l = []
f = open("test_data.txt")
for line in f:
elems = line[1:-1].split("', '")
l.append((elems[0], elems[1]))
f.close()
print l
Output:
[('32.42.4.120', '32.42.4.127'), ('32.42.5.128', '32.42.5.255'), ('32.42.15.136', '32.42.15.143'), ('32.58.129.0', '32.58.129.7'), ('32.58.131.0', '32.58.131.63'), ('46.7.0.0', '46.7.255.25')]

Categories

Resources