i want to add ints that is stored in a file and add the numbers to find the total.. i took this code from a txt book but im getting the following error :
invalid literal for int() with base 10: '1 2 3 12 4 55'
how can i solve this if i want to read the numbers one by 1 not by using a list
f = open("intgers.txt", 'r')
theSum = 0
for line in f:
line = line.strip()
number = int(line)
theSum += number
print("The sum is", theSum)
You need to split the line.
f = open("intgers.txt", 'r')
theSum = 0
for line in f:
numbers = line.strip().split(' ')
for number in numbers:
n = int(number)
theSum += n
print("The sum is", theSum)
Using this code block, you're assuming each of the numbers are separated by new lines in intgers.txt. As the error suggests, the line variable is '1 2 3 12 4 55'. You can't convert that to an integer. You need to parse this into a list of numbers first:
f = open("intgers.txt", 'r')
theSum = 0
for line in f:
numbers = line.split()
for num in numbers:
number = int(num.strip())
theSum += number
print("The sum is", theSum)
Look into uses of string methods strip() and split() if you're confused.
It appears that there are multiple space-separate integers on each line. You need to .split() each line and iterate over the resulting list to add the numbers from that line.
f = open("intgers.txt", 'r')
theSum = 0
for line in f:
splitline = line.strip().split()
for item in splitline:
number = int(item)
theSum += number
print("The sum is", theSum)
There are a number of improvements that can be made to this, using map to apply the int function across the list and using implicit iteration to get a sum directly from each line. For interest:
f = open("intgers.txt", 'r')
theSum = 0
for line in f:
theSum += sum(map(int, line.strip().split()))
print("The sum is", theSum)
Related
Basically, this is my task. Extract numbers from a text file and then calculate the sum of them.
I wrote the code successfully and but it doesn't work fine with 2 or more digit numbers and negative numbers. What should i do?
f = open('file6.txt', 'r')
suma = 0
file = f.readlines()
for line in file:
for i in line:
if i.isdigit() == True:
suma += int(i)
print("The sum is ", suma)
file6.txt:
1
10
Output:
The sum is 2
In your case, you are going line by line first through the loop and looking at every digit ( in second loop ) to add.
And /n at the end of elements make the .isDigit() function disabled to find the digits.
So your updated code should be like this :
f = open('file6.txt', 'r')
suma = 0
file = f.readlines()
for line in file:
if line.strip().isdigit():
suma += int(line)
print("The sum is ", suma)
Hope it helps!
Use re.split to split the input into words on anything that is not part of a number. Try to convert the words into numbers, silently skip if this fails.
import re
sum_nums_in_file = 0
with open('file6.txt') as f:
for line in f:
for word in re.split(r'[^-+\dEe.]+', line):
try:
num = float(word)
sum_nums_in_file += num
except:
pass
print(f"The sum is {sum_nums_in_file}")
This works for example on files such as this:
-1 2.0e0
+3.0
So I'm trying to calculate the sum and average of a text document filled with 10000 numbers.ยจ
This is my code:
with open("\\Users\\saksa\\python_courses\\1DV501\\assign3\\file_10000integers_A.txt", "r") as f:
total = 0
number_of_ints = 0
for line in f:
for i in line:
if i.isdigit() == True:
total += int(i)
number_of_ints +=1
print (total)
print (number_of_ints)
The document is formated like: 215, 631, 731, 225, 315, etc in multiple lines
The problem is that it reads every number 1 by 1. So 100 becomes 1 + 0 + 0.
I think I need to use split to make it work but I cant figure out how to.
You can iterate over each line in a file.
And you can split each line by a ',' and add each number
with open("\\Users\\saksa\\python_courses\\1DV501\\assign3\\file_10000integers_A.txt", "r") as f:
total = 0
number_of_ints = 0
for line in f:
print(line)
for num in line.split(','):
print(num)
total += int(num)
number_of_ints += 1
print(total)
print(number_of_ints)
You will need to add some logic to ensure the numbers are numbers
You should use split() function:
line = "110, 23400, 34569, 23567"
line.replace(" ", "") # Get rid of unnecessary spacebars
total = 0
number_of_ints = 0
for i in line.split(","):
# Here you can do whatever you want
try:
i = int(i)
total += int(i)
number_of_ints += 1
except:
pass
I have written a code that extracts floating point numbers from a
text file and produces a list of the numbers.
My challenge is summing the consecutive numbers and finding the
average of the numbers.
I am not allowed to use the sum function and I am new to python ..
this the code I have written so far ,
what can I do to add through the list
fh = open(fname)
for line in fh:
if line.startswith("X-DSPAM-Confidence:") : continue
# print(line)
count = 0
for line in fh:
if line.startswith("X-DSPAM-Confidence:"):
count = count + 1
# print(count)
for line in fh:
if line.startswith("X-DSPAM-Confidence:"):
# print(line)
xpos = line.find(' ')
# print(xpos)
num = line[xpos : ]
# print(float(num))
fnum = float(num)
# print(fnum)
total = 0
for i in fnum:
total += int(i)
print(total)
Error:"float object not iterable on line 24" ... line 24 is the 4th for loop
First an open file is iterable only once, and your code shows 4 loops starting with for line in fh:. After first loop, the file pointer will reach the end of file, and the following loops should immediately return. For that reason with should be prefered.
Next somewhere in the loop you get a float value in fnum. Just initialize total before starting the loop, and add fnum when you get it:
total = 0
with open(fname) as fh:
for line in fh:
if line.startswith("X-DSPAM-Confidence:"):
# print(line)
xpos = line.find(' ')
# print(xpos)
num = line[xpos : ]
# print(float(num))
fnum = float(num)
# print(fnum)
total += fnum
# print(total)
with ensures that the file will be cleanly closed at the end of the loop.
fnum is a float. It's not an array, therefore it's not iterable and cannot be iterated in a for loop.
You probably don't need an array to determine the total and the average:
fname = "c:\\mbox-short.txt"
fh = open(fname)
count = 0
total = 0
for line in fh:
if line.startswith("X-DSPAM-Confidence:"):
xpos = line.find(' ')
num = line[xpos : ]
fnum = float(num)
total += fnum
count += 1
print("Total = " + str(total))
print("Average = " + str(total / count))
print("Number of items = " + str(count))
You don't have to use startsWith in this case. Better to use split for each line of the file. Each line will split all the words to a list. Then using the indexes you look for, X-DSPAM-Confidence:. If it exists then take the corresponding value of interest. In this case it is index number 1. Below is the code:
total = 0
number_of_items = 0
with open("dat.txt", 'r') as f:
for line in f:
fields = line.split()
if fields != []:
if fields[0] == "X-DSPAM-Confidence:":
number_of_items += 1
total += float(fields[1])
print(total)
print(number_of_items)
avg = (total/number_of_items)
print(avg)
I saved your data in a text file names, "dat.txt".
Hope it helps !!!
I want to write a Python 3 script to read in an input file, like this:
8 13 67 43 47
9 19 5 3 69
93 21 25 53 20
and then count how many numbers are in the file and find the max. I wrote the following script:
file = open ("input.dat","r")
count = 0
for line in file :
parts = line.split()
count +=1
print (count)
But it only counts the number of lines. How do I count the number of numbers? In the file?
You said that you do not want to use lists. However, split() method acts on a string and converts it to a list. I'd focus my answer on the two requirements you specifically mentioned. If there are other requirements, please mention them in the comments below.
Counting the numbers
To do this, you can simply read each line, use split to break it into a list of numbers, and then add the length of that string to a running total.
Here's the code for the same:
file = open ("input.dat","r")
total_numbers = 0
for line in file :
parts = line.split()
total_numbers += len(parts)
print (total_numbers)
Finding the maximum number
As for finding the maximum number is present, for each line you can find the maximum number using inbuilt max function and select the maximum number out of the maximum numbers for each line.
This is how it can be achieved.
file = open ("input.dat","r")
total_numbers = 0
# Storing the most minimum number possible inside max_num
# '-inf' is a special string which implies tending to negative infinity
max_num = float('-inf')
for line in file :
parts = line.split()
# split() stores the numbers as a string inside the list
# map() converts the list of strings into a list of integers
parts = map(int, parts)
max_num_in_line = max(parts)
# If the maximum number in the line being read is more than max_num, replace max_num by that number
if max_num_in_line > max_num:
max_num = max_num_in_line
print (max_num)
I hope this helps. Do let me know if you need further clarification.
You can do everything you want easily using lists:
with open ("input.dat","r") as file:
data = file.read()
#Extract all integers in the file into 1 list
list_of_integers = [int(i) for i in x.replace('\n',' ').split()]
#Now you can whatever you please
count(list_of_integers)
max(list_of_integers)
sum(list_of_integers)
...
If you don't want to use list in your solution you can try this to calculate maximum number and count of all numbers
file = open ("input.dat","r")
count = 0
max = 0
for line in file :
#Reading file will result in list of numbers like ['1', '2', '3'], so you have to map them to int
parts = list(map(int, line.split()))
#Count of all numbers in a line
count = count + len(parts)
#Max number in a lint
max_iter = max(parts)
#Update max if previous max was smaller
if max_iter > max:
max = max_iter
print ("Total Numbers: {}, Maximum Number: {}".format(count,max))
file = open ("input.dat","r")
sum = 0
for line in file :
parts = line.split()
sum+=len(parts)
# Print the total number in a line
print (sum)
parts = map(int, parts)
max_in_line = max(parts)
if(max<max_in_line)
max = max_in_line
print(sum)
print(max)
import re
digit_count=0
number_count = 0
numbers = []
count=0
with open ("letters_and_numbers.txt") as f:
for line in f.readlines():
sub_strs = line.rstrip().split("-")
for i in range(0, len(sub_strs)):
file_words = re.split(r"[a-zA-Z\W]",sub_strs[i])
for word in file_words:
if word.isdigit():
digit_count += len(word)
number_count += 1
if i >=1 and sub_strs[i].startswith(word):
count-=int(word)
digit_count+=1
numbers.append("-")
numbers.append(word)
else:
count+=int(word)
numbers.append(word)
print "digits:",digit_count
print "amount of numbers:",number_count
print "numbers:",numbers
print "total:",count
This code counts the numbers in a file even if the file looks like this:
gfwgf8943758834y34ty3yttubf37t73
I have a code that relies on me reading a text file, printing off the numbers where there are numbers, printing off specific error messages where there are strings instead of numbers, then summing ALL the numbers up and printing their sum (then saving ONLY the numbers to a new text file).
I have been attempting this problem for hours, and I have what is written below.
I do not know why my code does not seem to be summing up properly.
And the python code:
f=open("C:\\Users\\Emily\\Documents\\not_just_numbers.txt", "r")
s=f.readlines()
p=str(s)
for line in s:
printnum=0
try:
printnum+=float(line)
print("Adding:", printnum)
except ValueError:
print("Invalid Literal for Int() With Base 10:", ValueError)
for line in s:
if p.isdigit():
total=0
for number in s:
total+=int(number)
print("The sum is:", total)
I have a code that relies on me reading a text file, printing off the
numbers where there are numbers, printing off specific error messages
where there are strings instead of numbers, then summing ALL the
numbers up and printing their sum (then saving ONLY the numbers to a
new text file).
So you have to do the following:
Print numbers
Print a message when there isn't a number
Sum the numbers and print the sum
Save only the numbers to a new file
Here is one approach:
total = 0
with open('input.txt', 'r') as inp, open('output.txt', 'w') as outp:
for line in inp:
try:
num = float(line)
total += num
outp.write(line)
except ValueError:
print('{} is not a number!'.format(line))
print('Total of all numbers: {}'.format(total))
This is a very short way to sum all numbers in your file (you will have to add try and except)
import re
print(sum(float(num) for num in re.findall('[0-9]+', open("C:\\Users\\Emily\\Documents\\not_just_numbers.txt", 'r').read())))
You are checking the wrong condition:
for line in s:
if p.isdigit():
p is this:
s=f.readlines()
p=str(s)
Being a strified version of a list, it will start with a '[', and hence p.isdigit() will always be false. You instead want to check line.isdigit(), and you want to only initialise total once instead of each time around the loop:
total = 0
for line in f:
if line.isdigit():
total += int(line)
Note that by iterating over f directly, you also don't need to ever call readlines().
Here is what you can do:
data.txt:
1
2
hello
3
world
4
code:
total = 0
with open('data.txt') as infile:
with open('results.txt', 'w') as outfile:
for line in infile:
try:
num = int(line)
total += num
print(num, file=outfile)
except ValueError:
print(
"'{}' is not a number".format(line.rstrip())
)
print(total)
--output:--
'hello' is not a number
'world' is not a number
10
$ cat results.txt
1
2
3
4
you can also try this:
f=open("C:\\Users\\Emily\\Documents\\not_just_numbers.txt", "r")
ww=open("C:\\Users\\Emily\\Documents\\not_just_numbers_out.txt", "w")
s=f.readlines()
p=str(s)
for line in s:
#printnum=0
try:
#printnum+=float(line)
print("Adding:", float(line))
ww.write(line)
except ValueError:
print("Invalid Literal for Int() With Base 10:", ValueError)
total=0
for line in s:
if line.strip().isdigit():
total += int(line)
print("The sum is:", total)
here str.strip([chars]) means
Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped
Every time you enter a new line you reset the total to zero if the number is a digit.
You might want your total to initialize before you enter the loop.
I tried debugging the for loop using the isdigit and isalpha
apparently every new line is not considered a digit or alphanumeric these always evaluate to false
As it turns out you don't need the for loop you've done most of the program with your try except statement
Here's how I did it on my system.
f = open("/home/david/Desktop/not_just_numbers.txt", 'r')
s = f.readlines()
p = str(s)
total = 0
for line in s:
#print(int(line))
printnum = 0
try:
printnum += float(line)
total += printnum
#print("Adding: ", printnum)
except ValueError:
print("Invalid Literal for Int() With Base 10:", ValueError)
print("The sum is: ", total)
$ echo -e '1/n2/n3/n4/n5' | python -c "import sys; print sum(int(l) for l in sys.stdin)"
Read from file containing numbers separated by new lines:
total = 0
with open("file_with_numbers.txt", "r") as f:
for line in f:
total += int(line)
print(total)