Reputation: 33
Ok im starting fresh and im going to bear everything I have exactly as it is.
NumbersMake.py
#This program writes 1 line of 12 random integers, each in the
#range from 1-100 to a text file.
def main():
import random
#Open a file named numbers.txt.
outfile = open('numbers.txt', 'w')
#Produce the numbers
for count in range(12):
#Get a random number.
num = random.randint(1, 100)
#Write 12 random intergers in the range of 1-100 on one line
#to the file.
outfile.write(str(num) + " ")
#Close the file.
outfile.close()
print('Data written to numbers.txt')
#Call the main function
main()
The code above produces a text file that says:
60 90 75 94 54 12 10 45 60 92 47 65
The numbers above are 12 randomly generated integers sepearted by a space.
Would it be easier in the second script if I removed the spaces?
NumbersRead.py
#This program reads 12 random integers, outputs each number
#to its own line and then outputs the total of the even and odd intergers.
def main():
#Open a file named numbers.txt.
infile = open('numbers.txt', 'r')
#Read/process the file's contents.
file_contents = infile.readline()
numbers = file_contents.split(" ")
odd = 0
even = 0
num = int(file_contents)
for file_contents in numbers:
if num%2 == 0:
even += num
else:
odd += num
#Close the file.
infile.close()
#Print out integer totals
print('The total of the even intergers is: ', even)
print('The total of the odd intergers is: ', odd)
#Call the main function
main()
The error I am receiving from the above script trying to process the total of the even and odd numbers is :
Traceback (most recent call last):
File "numbersread.py", line 29, in <module>
main()
File "numbersread.py", line 14, in main
num = int(file_contents)
ValueError: invalid literal for int() with base 10: '60 90 75 94 54 12 10 45 60 92 47 65 '
I dont know what I am doing wrong.
Upvotes: 1
Views: 515
Reputation: 180481
Presuming you have a list like ["1","2","3"...]
odd = sum(int(x) for x in numbers if x % 2)
even = sum(int(x) for x in numbers if not x % 2)
The best way is to use with
to open your files and map to int first:
with open('numbers.txt') as f: # closes you files automatically
numbers = map(int,f.read().split())
odd = sum(x for x in numbers if x % 2)
even = sum(x for x in numbers if not x % 2)
If you had a very large file you would iterate over each line and sum as you go.
Also you only read a single line using readline
, if you want only the first line replace f.read().split()
with f.readline().split()
sum(x for x in numbers if x % 2)
is a generator expression, Variables used in the generator expression are evaluated lazily when the next() method is called for generator object
Upvotes: 2
Reputation: 797
This looks suspiciously like homework to me, but here's what I'd put in place of your while loop
for num_str in numbers:
num = int(num_str)
if num%2 == 0: #Even
even += num
else:
odd += num
Upvotes: 0