So, I'm doing this assignment and I can't seem to figure out how to continue on to the next step.
assignment output example
The file numbers.txt contains the following numbers all on separate lines (25, 15, 5, six, 35, one, 40).
My problem is that I can only print out one ValueError message (six), but I need to be able to print out both messages (invalid literal for int() with base 10: 'six\n', invalid literal for int() with base 10: 'one\n').
Since I can't get the codes to move on to the next iteration, my average only adds 25, 15, and 5.
I've only been learning Python for a month so I don't know if there's a simple way to solve all these problems.
Below is the code I am working on.
def main():
while True:
try:
filename = input("Enter a file name: ")
infile = open(filename, "r")
except IOError:
print("[Error No. 2] No such file or directory:", filename)
continue # continue to next iteration
else:
break
data = infile.readline().strip()
numbers = data.split()
total = 0
count = 0
try:
infile = open(filename, "r") #somehow without this, the first line won't print
for line in infile:
num = int(line)
print(num)
total += num
count += 1
print("The average is: ", total/count)
except ValueError as err:
print(err)
finally:
print(total/count)
main()
You can repositioning your try statement in the second loop like so:
data = infile.readline().strip()
numbers = data.split()
total = 0
count = 0
infile = open(filename, "r")
for line in infile:
try:
num = int(line)
print(num)
total += num
count += 1
except ValueError as err:
print(err)
print("The average is: ", total/count)
This way, you won't exit the loop once you encounter an error message, and will simply print it and move on to the next line.
Try the below
# open the file using 'with' - it will make sure that the file will be closed
with open('input.txt') as f:
values = []
# read the lines into a list
lines = [l.strip() for l in f.readlines()]
for line in lines:
# try to convert to int
try:
x = int(line)
values.append(x)
except ValueError as e:
print(e)
# calculate the average
print(f'Avg: {sum(values)/len(values)}')
input.txt
25
15
5
six
35
one
40
output
invalid literal for int() with base 10: 'six'
invalid literal for int() with base 10: 'one'
Avg: 24.0
You need to indent your while True as currently the main function is causing an error.
You should also do an if line == ‘six’:
line = 6
You can set the try-except block inside the for loop which should produce the correct results.
data = infile.readline().strip()
numbers = data.split()
total = 0
count = 0
infile = open(filename, "r")
for line in infile:
try:
num = int(line)
total += num
count += 1
except ValueError as err:
print(err)
print("The average is: ", total/count)
Related
This is the code to search a particular entry in a file:
num2find = str(input("Enter a number to find: "))
test_file = open("testfile.txt", "r")
num = "0"
flag = False
while (num != ""):
num = test_file.readline()
if (num == num2find):
print("Number found.")
flag = True
break
if not flag:
print("\nNumber not found.")
The test file is:
1
2
3
4
5
If I input 2, the code still outputs "Number not found."
Every time you read a line from a text file, you are getting "\n" at the end of the string line, so the problem you are facing is that you are comparing "2" to "2\n" which is not the same.
You could take advantage of with to pen your file. This way you do not need to worry about closing the file once you are done with it. Also, you do not need to pass the "r" argument since it is the default mode for open.
You should use a for loop instead of that needless while loop. The for loop will terminate automatically when all the lines in the file have been read.
One more improvement you could make is to rename the flag flag to found, and to print the result once the file has been processed.
num2find = int(input("Enter a number to find: "))
found = False # rename flag
with open("testfile.txt") as test_file: # use with to avoid missing closing the file
for line in test_file: # use a for loop to iterate over each line in the file
num = int(line)
if num == num2find:
found = True
break
if found: # print results at the end once file was processed
print("Number found.")
else:
print("Number not found.")
Each line in the test file contains two characters - the number and a newline. Since "2" does not equal "2\n", your number is not being found. To fix this, use the int function to parse your lines, since it ignores whitespace (like the \n) character:
num2find = int(input("Enter a number to find: "))
flag = False
with open("testfile.txt", "r") as test_file:
for line in test_file:
num = int(line)
if num == num2find:
print("Number found.")
flag = True
break
if not flag:
print("\nNumber not found.")
The easiest and the most logical solution I could come up with after all the feedback was this:
num2find = int(input("Enter a number to find: "))
file_data = open("testfile.txt", "r")
found = False
for data in file_data:
if int(data) == num2find:
found = True
if found:
print("\nNumber found.")
else:
print("\nNumber not found.")
file_data.close()
You need to add .rstrip() on num = test_file.readline()
Try something like this:
num2find = str(input("Enter a number to find: "))
test_file = open("testfile.txt", "r")
file_data = test_file.readlines()
flag = False
for item in file_data:
if num2find == item.rstrip():
flag = True
break
if not flag:
print("\nNumber not found.")
else:
print("Number found")
Don't use .readline() like that, use readlines() instead
When I'm running the program it is outputting that no countries exist starting with that letter, when in fact they exist. Can someone tell me what I'm doing wrong or maybe give me an alternate way to only output countries starting with the wanted letter. This is my code:
#Creating the list
CountryList = []
CountryandPopulationList = []
#Creating the Function1
def Function1(fh,letter):
count = 0
#Adding the file to the list
for word in fh:
CountryandPopulationList.append(word)
index = word.find('-')
Country = word[0:index]
CountryList.append(Country.strip())
#Printing countries starting with chosen letter
try:
for i in CountryList:
if(i[1]== letter):
print(i)
count = count + 1
else:
print('The letter does not exist')
except IndexError:
print('Total number of countries starting with letter',letter,'=',count )
#Asking user to input letter
letter = input('Enter the first letter of the country: ')
#Opening the file
try:
fh = open('D:\FOS\\Countries.txt','r')
except IOError:
print('File does not exist')
else:
function1 = Function1(fh,letter)
Thank you
Please also provide the input format of your Countries.txt file as well as the python version you are using s.t. it is easier to help you.
For a start: open() will not provide you with the file content but only gives you the textwrapper object. Try changing the line to
fh = open('D:\FOS\...\Countries.txt', 'r').read()
A slightly simpler version. Try this:
def function1(fh, letter):
count = 0
country_list = [line.split('-')[0].strip() for line in fh.readlines()]
for country in country_list:
if country.lower().startswith(letter.lower()):
count += 1
print(country)
print("Total number of countries starting with letter '%s'= %d" % (letter, count))
#Asking user to input letter
letter = input('Enter the first letter of the country: ')
#Opening the file
try:
with open('D:\FOS\\Countries.txt','r') as fh:
function1(fh, letter)
except IOError:
print('File does not exist')
I'm trying to make a new file at the end of a program to append info into, however the file isn't being created for some reason (the place in my code to look at is the #curve area). My best guess is that the variable "filename" established at the beginning of the program, isn't carrying all the way down to where I establish the new file name. My code is as follows:
import statistics
# input
filename = input("Enter a class to grade: ")
try:
# open file name
open(filename+".txt", "r")
print("Succesfully opened", filename,".txt", sep='')
print("**** ANALYZING ****")
with open(filename+".txt", 'r') as f:
counter1 = 0
counter2 = 0
right = 0
answerkey = "B,A,D,D,C,B,D,A,C,C,D,B,A,B,A,C,B,D,A,C,A,A,B,D,D"
a = []
# validating files
for line in f:
if len(line.split(',')) !=26:
print("Invalid line of data: does not contain exactly 26 values:")
print(line)
counter2 += 1
counter1 -= 1
if line.split(",")[0][1:9].isdigit() != True:
print("Invalid line of data: wrong N#:")
print(line)
counter2 += 1
counter1 -= 1
if len(line.split(",")[0]) != 9:
print("Invalid line of data: wrong N#:")
print(line)
counter2 += 1
counter1 -= 1
counter1 += 1
#grading students
score = len(([x for x in zip(answerkey.split(","), line.split(",")[1:]) if x[0] != x[1]]))
score1 = 26 - score
score2 = score1 / 26
score3 = score2 * 100
a.append(score3)
sscore3 = str(score3)
# results file
results = open(filename+"_grades.txt", "a")
results.write(line.split(",")[0])
results.write(",")
results.write(sscore3[:2])
results.write("\n")
results.close()
# in case of no errors
if counter2 == 0:
print("No errors found!")
# calculating
number = len(a)
sum1 = sum(a)
max1 = max(a)
min1 = min(a)
range1 = max1 - min1
av = sum1/number
# turn to int
av1 = int(av)
max2 = int(max1)
min2 = int(min1)
range2 = int(range1)
# median
sort1 = sorted(a)
number2 = number / 2
number2i = int(number2)
median = a[number2i]
median1 = int(median)
# mode
from statistics import mode
mode = mode(sort1)
imode = int(mode)
# printing
print ("**** REPORT ****")
print ("Total valid lines of data:", counter1)
print ("Total invalid lines of data:", counter2)
print ("Mean (average) score:", av1)
print ("Highest score:", max2)
print("Lowest score:", min2)
print("Range of scores:", range2)
print("Median Score:", median1)
print("Mode score(s):", imode)
# curve
part = input("Would you like to apply a curve to the scores? (y)es or (n)o?")
if part == "y":
newmean = input("Enter desired mean score:")
part1 = newmean - av1
part2 = sscore3 + part1
results = open(filename+"_grades_with_curve.txt", "a")
results.write(line.split(",")[0])
results.write(",")
results.write(sscore3[:2])
results.write(",")
results.write(part2)
results.write("\n")
results.close()
except:
print("File cannot be found.")
and It skips to the except block when I enter "y" at the end to try and create the new list, meaning the issue is within creating this new list.
The code is too long and requires reorganization.
It is likely, there are other problems with your code and you are trying to fix wrong one.
Few hints:
Do not open file without assigning the file object to a variable
open(filename+".txt", "r")
You open the file and have no chance to close it as you ignore the returned
file object.
Use with block to open/close your files
with open(input_fname, 'r'):
# work with the file
Learn doing so everywhere.
Do not reopen file for writing results
Your code repeatedly opens the result file (in "a" mode). You have better opening it only once.
You may even open multiple files within one context block:
with open(input_fname, 'r') as f, open(output_fname, "a") as results:
# work with the files
Reuse once calculated result
In many places you split the line: line.split(",").
You shall put the result into variable and reuse it.
rec = line.split(",")
Never ignore exceptions!!! (most serious problem)
The final block is catching all exceptions without giving you any sign, what went wrong (or even
worse, it tells you probably wrong information that the file was not found).
So instead of:
try:
# some code
except:
print("File not found.")
at least reraise the exception to learn from it:
try:
# some code
except:
print("File not found.") # this is probably to be removed as misleading message
raise
In fact, you can completely ignore complete top level try - except block and let the exception show
up telling you what went wrong.
Split your code into smaller chunks.
Having the code split to smaller functions shall simplify debugging and usage
I am trying to count all numbers in given file. It works unless there is a word between a numbers.
e.g:
1
2
car
3
4
Here's my code:
def main():
count=0
with open("numbers.txt", "r") as f:
try:
line = f.readline()
while line != '':
print(line.strip())
count += int(line)
line = f.readline()
except Exception as err:
print(err)
print(count)
main()
I was thinking about continue, but it does only work with for or while. So is there any way?
You should move the try and except blocks inside your loop. Then when you hit a line with a non-number, you'll just skip it and go on the the next line.
Unrelated to that error, you can also simplify your code a bit by iterating over the file directly in a for loop, rather than calling readline repeatedly in a while loop:
with open("numbers.txt", "r") as f:
for line in f: # simpler loop
print(line.strip())
try: # move this inside the loop
count += int(line)
except Exception as err: # you may only want to catch ValueErrors here
print(err)
print(count)
you can use isdigit to check for number:
while line != '':
print(line.strip())
if line.strip().isdigit():
count += int(line.strip())
line = f.readline()
Here is Pythonic way to achieve this
if you want to sum all digit:
f = open('file')
total_count = sum(int(x) for x in f if x.strip().isdigit())
if you want to count how many of them are digit:
f = open('file')
total_digit = len(x for x in f if x.strip().isdigit())
You can use the isdigit method to check if the line contains only numbers:
def main():
count=0
with open("numbers.txt", "r") as f:
count = sum(int(line) for line in f if line.strip().isdigit())
print(count)
if __name__ == '__main__':
main()
You can try using regular expressions:
import re
total = 0
with open("numbers.txt", "r") as f:
line = f.readline()
while line != '':
total += sum([int(x) for x in re.findall('(\\d+)', line)])
line = f.readline()
print total
fileName = raw_input("Enter the filename: ")
n = input("Enter the line you want to look: ")
f = open(fileName,'r')
numbers = []
for line in f:
sentenceInLine = line.split('\n')
for word in sentenceInLine:
if word != '':
numbers.append(word)
print numbers
print len(numbers)
print numbers[n-1]
if n == 0:
print "There is no 0 line"
break
i think you missed to split sentenceInLine like sentenceInLine.split(' ')
You are looping over each line, then you split lines based on '\n'. That \n is a line break character. That would confuse your logic right there.
So it is a bit confusing what you are trying to do but you should check n after the user has inputed a value for n. not at the end.
You may want to also catch the exception where file cannot be found I think this is what you need:
fileName = raw_input("Enter the filename: ")
n = input("Enter the line you want to look: ")
if n == 0:
print "There is no 0 line"
sys.exit();
try:
f = open(fileName,'r')
except IOError:
print "Could not find file"
sys.exit()