How do I tell a user where the line error occurred? - python

I'm trying to incorporate enumerate so I can give the user of the program where the line error was and the input of that line.
Here is my code:
elif response == 'data2':
print('Processing file:', response + '.txt')
try:
infile = open('data2.txt', 'r')
for line in infile:
amount = float(line)
total += amount
infile.close()
print(format(total, ',.2f'))
except IOError:
print("IO Error occurred trying to read the file.")
except ValueError:
print("Non-numeric data found in file:", response + '.txt')
except:
print("An error occurred.")
As you see I want the ValueErrorto output something along the lines of:
Non-numeric data found in file: data2.txt at line: 3 with input: three
hundred
I'm however stuck on how to accomplish this.

You can use the enumerate built-in function to get the line number:
elif response == 'data2':
print('Processing file:', response + '.txt')
try:
# Python allows you to iterate over a file object directly.
for line_no, line in enumerate(open('data2.txt', 'r')):
amount = float(line)
total += amount
print(format(total, ',.2f'))
except IOError:
print("IO Error occurred trying to read the file.")
except ValueError:
# I took the liberaty of formatting your output in a way
# that's a bit more readble than one long line of text.
print("Non-numeric data found in file: {}.txt at line: {}"
"with input: {}".format(response, line_no + 1, line))
except:
print("An error occurred.")

You need to track what line you are up to in the file, and catch the exception while reading.
for line_number, line in enumerate(infile, 1):
try:
amount = float(line)
except ValueError:
print(
"Non-numeric data found in file",
response + ".txt on line",
line_number,
"with input",
line
)
exit(1) # or whatever is appropriate for this script.

Related

Rerun code if file doesn't exist is not working

I have this code to read a file
def collect_exp_data(file_name):
data = dict()
while True:
try:
with open(file_name, 'r') as h:
break
for line in h:
batch, x, y, value = line.split(',')
try:
if not batch in data:
data[batch] = []
data[batch] += [(float(x), float(y), float(value))]
except ValueError:
print("\nCheck that all your values are integers!")
except FileNotFoundError:
print("\nThis file doesn't exist, Try again!")
return data
I'm trying to add some error handling, i want to re ask the user to enter file in case the file doesn't exist, but the code is just returning an endless loop!
what did I do wrong and how can I fix it?
Edit:
If i try and take the while loop outside, then it works in case file doesn't exists, but if file exists, the code is just stopping after the loop and not running next function, here is the code
def collect_exp_data(file_name):
data = dict()
with open(file_name, 'r') as h:
for line in h:
batch, x, y, value = line.split(',')
try:
if not batch in data:
data[batch] = []
data[batch] += [(float(x), float(y), float(value))]
except ValueError:
print("\nCheck that all your values are integers!")
return data
while True:
file_name = input("Choose a file: ")
try:
data = collect_exp_data(file_name)
break
except FileNotFoundError:
print('This file does not exist, try again!')
Make a condition to break the loop
finished = False
while not finished:
file_name = input("Choose a file: ")
try:
data = collect_exp_data(file_name)
# we executed the previous line succesfully,
# so we set finished to true to break the loop
finished = True
except FileNotFoundError:
print('This file does not exist, try again!')
# an exception has occurred, finished will remain false
# and the loop will iterate again
Do all your exception handling in the main function.
def collect_exp_data(filename):
data = dict()
with open(filename) as infile:
for line in map(str.strip, infile):
batch, *v = line.split(',')
assert batch and len(v) == 3
data.setdefault(batch, []).extend(map(float, v))
return data
while True:
filename = input('Choose file: ')
try:
print(collect_exp_data(filename))
break
except FileNotFoundError:
print('File not found')
except (ValueError, AssertionError):
print('Unhandled file content')
Obviously the assertion won't work if debug is disabled but you get the point

Try/Except Block causing ValueError

for my coding assignment I am to create a file that will read a csv file, offer different attributes to do analysis over (determined by the column values. I had this code working perfectly, but after I added my first try/except block I started getting the following error:
Traceback (most recent call last): File
"/Users/annerussell/Dropbox/Infotec 1040/module 8/csval.py", line 49,
in
row1=next(reader, 'end')[0:] ValueError: I/O operation on closed file.
Here is a link to a file you can test it with if desired. As you probably guessed this is a class assignment, and I am working on learning python for gradschool anyway so any suggestions are greatly appreciated.
import csv
print('Welcome to CSV Analytics!')
# Get file name and open the file
while True:
try:
file_name = input('Enter the name of the file you would like to process: ')
with open(file_name, "rt") as infile:
# Select the attribute to be analyzed
reader=csv.reader(infile)
headers=next(reader)[0:]
max=len(headers)
except FileNotFoundError:
print('The file you entered could not be found. Please' \
+ ' enter a valid file name, ending in .csv.')
continue
except IOError:
print('The file you selected could not be opened. Please ' \
+ 'enter a valid file name, ending in .csv.')
continue
except:
print('There was an error opening or reading your file. Please ' \
+ 'enter a valid file name, ending in .csv.')
continue
else:
print ('The attributes available to analyse are:')
for col in range(1, max):
print(col, headers[col])
while True:
try:
choice=int(input('Please select the number of the attribute you would like to analyze '))
except:
print('Please enter the numeric value for the selection you choose.')
continue
else:
# Build a dictionary with the requested data
dict1= {}
numrows=-1
row1=[]
largest_value=0
key_of_largest_value=0
while row1 != 'end':
row1=next(reader, 'end')[0:]
if row1 !='end':
numrows += 1
key=row1[0]
value=float(row1[choice])
dict1[key] = value
if value>largest_value:
largest_value=value
key_of_largest_value=key
# print('dictionary entry ( key, value)', key, value)
print('Largest ', headers[choice], ' value is ', key_of_largest_value, ' with ', largest_value)
In short: After with block ends, file is closed. You can't read from it, reader will fail.
Probably you didn't notice there is one-space indent for with, replace it with common indent so it will be more clear.
Seach for python context manager for more deep understanding.
Suggestion here is to factor out all logic from try else block to process_file function, and call it inside with statement.
with open(file_name, "rt") as infile:
# Select the attribute to be analyzed
reader=csv.reader(infile)
headers=next(reader)[0:]
max=len(headers)
process_file(reader, headers, max) # <-- like that
using with you need to move second condition to it block or
replace
with open(file_name, "rt") as infile:
with
isProcessing = True
while isProcessing:
....
infile = open(file_name, "rt")
...
#end of line
#print('Largest ',....
infile.close()
# end the loop
isProcessing = False

Reading Data from a File in Python with Exceptions

I have to write a program that will read data from a file, convert it to an integer and total the amount. So far here is what i have. The numbers from the data file "numdata.txt" are: 78,93,85,100,81,76,94,77.
def main():
total = 0
try:
NumberFile = open('numdata.txt', 'r')
for line in NumberFile:
amount = float(line)
total += amount
print(format(total, ',.2f'))
except IOError:
print('An error occurred trying to read the file.')
except ValueError:
print('Non-numeric data found in the file.')
except:
print('An error has occurred.')
finally:
NumberFile.close()
main()
When i run the program the first number (78) gets displayed and then one of the exception error messages comes up, the weird thing is that it's different sometimes. If someone could help point me in the right direction I'd appreciate it. I'm still very new to this so please bear with me.
I tried and tried but could not get the loop to work correctly so i ended up going this route:
def main ():
infile = open('numdata.txt', 'r')
num1 = int(infile.readline())
num2 = int(infile.readline())
num3 = int(infile.readline())
num4 = int(infile.readline())
num5 = int(infile.readline())
num6 = int(infile.readline())
num7 = int(infile.readline())
num8 = int(infile.readline())
infile.close()
total = num1+num2+num3+num4+num5+num6+num7+num8
average = total/8
print('the total: ', total)
print('the average: ', average)
main()
It's not pretty but it works i guess lol
total = 0
try:
NumberFile = open('numdata.txt', 'r')
for line in NumberFile:
amount = float(line)
total += amount
print(format(total, ',.2f'))
except IOError:
print('An error occurred trying to read the file.')
except ValueError:
print('Non-numeric data found in the file.')
except:
print('An error has occurred.')
finally:
NumberFile.close()
The exception occurs because you're closing the file immediately after the first iteration, leaving you unable to iterate over the rest of it.
Moving NumberFile.close() to a finally clause ensures the file is closed no matter what goes wrong. However, a much better way to read / write files in Python is to use the with keyword, which is a built-in method of ensuring the same thing.
total = 0
with open('numdata.txt', 'r') as f:
for line in f:
try:
total += float(line)
except ValueError:
print('Non-numeric data found in the file.')
continue
finally:
print('{:.2f}'.format(total, ',.2f'))
you are closing the file in first iteration NumberFile.close() is not indented properly

Getting Unexpected EOF while parsing

trying to make a file that opens an existing text file and looks for a line number in that file. If the line number is not there I want it to print out a message that says that it is not in there.
This is what i have so far. And i am getting the Unexpected EOF error message. Where am I missing the problem?
# Get Input from user
file_name = input("Name of file to open please: ")
try:
in_file=open(file_name)
while True:
find_line = input("Which line number are you looking for? ")
try:
line_num=int(find_line)
line_count=1
for line_num in in_file:
if line_count== find_line:
print("Line number {} of the file {}, reads: {}".format(find_line,file_name,line_num))
break
line_count+=1
else:
print("Line number {} in file {} seems to be missing".format(find_line,file_name))
in_file.close()
in_file.open(file_name)
continue
break
except ValueError:
print("The Line Number you entered",find_line,"is not a correct line number")
in_file.close()
except IOError:
print ("Not sure how to break this to you, but the file your requested",file_str,"well, it's just not there")
print ("end of program")
That is to be expected. Your first try block doesn't have an except block.
try:
# Your code goes here
except:
print("Error")

inputting a words.txt file python 3

I am stuck why the words.txt is not showing the full grid, below is the tasks i must carry out:
write code to prompt the user for a filename, and attempt to open the file whose name is supplied. If the file cannot be opened the user should be asked to supply another filename; this should continue until a file has been successfully opened.
The file will contain on each line a row from the words grid. Write code to read, in turn, each line of the file, remove the newline character and append the resulting string to a list of strings.After the input is complete the grid should be displayed on the screen.
Below is the code i have carried out so far, any help would be appreciated:
file = input("Enter a filename: ")
try:
a = open(file)
with open(file) as a:
x = [line.strip() for line in a]
print (a)
except IOError as e:
print ("File Does Not Exist")
Note: Always avoid using variable names like file, list as they are built in python types
while True:
filename = raw_input(' filename: ')
try:
lines = [line.strip() for line in open(filename)]
print lines
break
except IOError as e:
print 'No file found'
continue
The below implementation should work:
# loop
while(True):
# don't use name 'file', it's a data type
the_file = raw_input("Enter a filename: ")
try:
with open(the_file) as a:
x = [line.strip() for line in a]
# I think you meant to print x, not a
print(x)
break
except IOError as e:
print("File Does Not Exist")
You need a while loop?
while True:
file = input("Enter a filename: ")
try:
a = open(file)
with open(file) as a:
x = [line.strip() for line in a]
print (a)
break
except IOError:
pass
This will keep asking untill a valid file is provided.

Categories

Resources