I am trying to make a program which grabs a list of numbers from a file (which could change in lines and size), and then print out the total of all the numbers and the average. I had no problems doing this when I had a set number of linereads, but am confused on the ‘proper’ way when the lineread changes every run.
This is my work-in-progress code. I read around a bit and found the correct (?) way of looping through the file to find the length, but not sure how to implement it since it throws some type of IO error currently. Thanks for the help!
def main():
filename = input("Enter file name (name.txt):")
try:
file = open(filename, "r")
except IOError:
print("Error opening file!")
totalLines = totalLineGet(filename)
results = []
for x in range(totalLines):
results.append(getLineNumber(x+1, file))
print("Total = ", numTotal)
print("Average = ", numAvg)
def totalLineGet(_filename):
count = 0
_file = open(_filename, "r")
for x in open(_file):
count+= 1
return count
def getLineNumber(linetoget, _file):
try:
intNumber = int(number = _file.readline())
except ValueError:
print("Error in file data!")
return intNumber
main()
I’m not sure what you want to do… but you should be able to get the answer in one pass.
You can use
enumerate()to number an iterable object, in this case a file, if you need to know the item/line number count.Assuming a single int() per line:
if this is CSV data you should look into using the
csvmodule, it will split the line into rows/columns for you.