I'm trying to catch the FileNotFoundError and break the code when it occurs, but for some reason it's not working, im still getting the error and the code is not breaking, here is my code
file_name = input("Choose a file: ")
def split_columns(file_name):
x_values = []
y_values = []
try:
with open(file_name) as f:
for line in f:
row_values = line.split()
print(row_values)
x_values.append(float(row_values[0]))
y_values.append(float(row_values[1]))
except FileNotFoundError:
print('This file does not exist, try again!')
raise
return x_values, y_values
What did i do wrong?
Take the try/except out of the function, and put it in the loop that calls the function.
def split_columns(file_name):
x_values = []
y_values = []
with open(file_name) as f:
for line in f:
row_values = line.split()
print(row_values)
x_values.append(float(row_values[0]))
y_values.append(float(row_values[1]))
return x_values, y_values
while True:
file_name = input("Choose a file: ")
try:
x_values, y_values = split_columns(file_name)
break
except FileNotFoundError:
print('This file does not exist, try again!')
Related
Anybody can advise what could be wrong with my code?
I am trying to make a method that removes the single line comments from the content.
Also, the method should return the single line comments that start with '#'.
import os
def deleteComments(file):
try:
my_file = open(file, 'r')
data = my_file.read()
clean = ""
comment= 0
if i[0] == "#":
comment += 1
else:
pass
with open("clean-", "w") as f:
f.write(clean)
f.close()
my_file.close()
except:
print("An error occurred with accessing the files")
return file
def deleteComment(file):
try:
my_file = open(file, 'r')
data = my_file.read()
clean = ""
comment= 0
if i[0] == "#":
comment += 1
else:
pass
with open("clean-", "w") as f:
f.write(clean)
f.close()
my_file.close()
except:
print("An error occurred with accessing the files")
return file
This should make it work.
import os
def deleteComments(file):
try:
my_file = open(file, 'r')
data = my_file.read()
clean = ""
comments_count = 0
for i in data.split('\n'):
if i[0] == "#":
clean += i
clean += '\n'
comments_count += 1
else:
pass
name = os.path.basename(path)
with open("clean-" + name, "w") as f:
f.write(clean)
f.close()
my_file.close()
return comments_count
except:
print("An error occurred with accessing the files")
return file
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
I have a pickle db with 5 variable in it that goes : rafTur, rafKat, rafNo, rafIndex, rafIndexData. I'm trying to delete a data inside my pickle file. My main goal is taking an input from user that goes like this :
rafTur = S rafKat = 1 rafNo = 2 rafIndex = 3
And then finding that imput from my pickle file that named noSqlDB. and then delete the entire data about input.
def delPic():
infile = open('noSqlDB', 'rb+')
sistem = pickle.load(infile)
flag = False
rafTur = str(input('Rafın türünü giriniz : '))
rafKat = int(input('Rafın katını giriniz : '))
rafNo = int(input('Rafın Nosunu giriniz : '))
rafIndex = int(input('Rafın indexini giriniz : '))
# read to the end of file.
for x in range((len(sistem) + 1)):
try:
if (sistem['rafTur'].upper() == rafTur.upper() and sistem['rafKat'] == rafKat and sistem['rafNo'] == rafNo and sistem['rafIndex'] == rafIndex):
del sistem
flag = True
sistem = pickle.load(infile)
except EOFError:
break
if flag == False:
print('Record not Found')
infile.close()
When i run this code nothing changes. The data stays on noSqlDB. How can i delete the data inside the noSqlDB ? like this
I tried changing
del sistem
to
del sistem['rafTur'],sistem['rafKat'], sistem['rafNo'],sistem['rafIndex'],sistem['rafIndexData']
def unpickle_database(filename):
with open(filename, 'rb') as f:
while True:
try:
yield pickle.load(f)
except EOFError:
break
def save_object(obj, filename,a):
if a < 1:
with open(filename, 'wb+') as output:
pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL)
else :
with open(filename, 'ab+') as output:
pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL)
def delPic():
temp =0
students = list(unpickle_database('noSqlDB'))
for student in students:
print(student)
save_object(student, 'noSqlDB',temp)
temp += 1
Found a solution after trying some code here it is.
I want to make a limit (say three times) to the attempts when trying to open file and the file cannot be found.
while True:
inputfilename = input('Type the filename then press enter: ')
try:
inputfile = open(inputfilename,"r", newline='')
except FileNotFoundError:
print ('File does not exist')
print ('')
else:
break
The result of the code above, there is no limit. How can I put the limit in the above codes.
I am using python 3.5.
Replace while True: by for _ in range(3):
_ is a variable name (could by i as well). By convention this name means you are deliberately not using this variable in the code below. It is a "throwaway" variable.
range (xrange in python 2.7+) is a sequence object that generates (lazily) a sequence between 0 and the number given as argument.
Loop three times over a range breaking if you successfully open the file:
for _ in range(3):
inputfilename = input('Type the filename then press enter: ')
try:
inputfile = open(inputfilename,"r", newline='')
break
except FileNotFoundError:
print ('File does not exist')
print ('')
Or put it in a function:
def try_open(tries):
for _ in range(tries):
inputfilename = input('Type the filename then press enter: ')
try:
inputfile = open(inputfilename, "r", newline='')
return inputfile
except FileNotFoundError:
print('File does not exist')
print('')
return False
f = try_open(3)
if f:
with f:
for line in f:
print(line)
If you want to use a while loop then the following code works.
count = 0
while count < 3:
inputfilename = input('Type the filename then press enter: ')
try:
inputfile = open(inputfilename,"r", newline='')
count += 1
except FileNotFoundError:
print ('File does not exist')
print ('')
So I am trying to write a piece of code to take text from a file, move into a dictionary and then process it. I keep getting this error:
File "C:\Users\Oghosa\Assignment2.py", line 12, in <module>
builtins.IndexError: string index out of range
Here's my program:
endofprogram = False
dic = {}
try:
filename = input("Please Enter the Filename:")
infile = open(filename, 'r')
except IOError:
print("Error Reading File! Program ends here!")
endofprogram = True
if endofprogram == False:
for line in infile:
line = line.strip("\n")
if (line != " ") and (line[0] != "#"):
item = line.split(":")
print(items)
dic["Animal id"] = item[0]
dic["Date"] = item[1]
dic["Station"] = item[2]
print(dic)
Can someone aid in pointing out my mistake please?
Here's a sample input text:
#Comments
a01:01-24-2011:s1
a03:01-24-2011:s2
<blank line>
<blank line>
a02:01-24-2011:s2
a03:02-02-2011:s2
a03:03-02-2011:s1
a02:04-19-2011:s2
<blank line>
#comments
a01:05-14-2011:s2
a02:06-11-2011:s2
a03:07-12-2011:s1
a01:08-19-2011:s1
a03:09-19-2011:s1
a03:10-19-2011:s2
a03:11-19-2011:s1
a03:12-19-2011:s2
Well, you should at least print the offending line so you know what the culprit is:
for line in infile:
items = line.strip("\n")
try:
if (line.strip != "") and (items[0] != "#"):
items = line.split(":") #i dont like your reuse of line so changing to items
....
except IndexError: #if python 3 use except IndexError as e:
print(items) #prints offending line
endofprogram = False
attrs=["Animal id","Date","Station"]
dictionary=[]
try:
# filename = input("Please Enter the Filename:")
infile = open('rite.txt', 'r')
except IOError:
print("Error Reading File! Program ends here!")
endofprogram = True
if endofprogram == False:
for line in infile:
line = line.strip("\n")
if (line != "") and (line[0] != "#"):
item = line.split(":")
dictionary.append(dict(zip(attrs, item)))
print dictionary
Your problem is that when there are blank lines in the file, line[0] doesn't exist. To fix this problem try this version:
endofprogram = False
dic = {}
try:
filename = input("Please Enter the Filename:")
infile = open(filename, 'r')
except IOError:
print("Error Reading File! Program ends here!")
endofprogram = True
if endofprogram == False:
for line in infile:
line = line.strip("\n")
if len(line):
if line[0] != "#":
item = line.split(":")
print(items)
dic["Animal id"] = item[0]
dic["Date"] = item[1]
dic["Station"] = item[2]
print(dic)
Also worth noting is that you are overwriting dic on each iteration of the loop. So after the loop is done; dic will only contain information from the last line of the file.
The problem is you weren't checking for empty lines correctly in the
if (line != " ") and (line[0] != "#"):
statement. This is because they wouldn't even have a space left in them after line = line.strip("\n") executed, so just about any indexing operation will fail.
The code below has that and several other coding errors fixed. Note it's important to post your actual code here to make it easier for people to help you.
endofprogram = False
dic = {}
try:
filename = input("Please Enter the Filename:")
infile = open(filename, 'r')
except IOError:
print("Error Reading File! Program ends here!")
endofprogram = True
if not endofprogram:
for line in infile:
line = line.strip("\n")
if line and line[0] != "#":
items = line.split(":")
print(items)
dic["Animal id"] = items[0]
dic["Date"] = items[1]
dic["Station"] = items[2]
print(dic)
Do you have a blank line in your file? On line 12 you may want to check that the line has text before indexing it using line[0]. Do you really have a line with an empty string of should line 12 really read:
if line.strip() and (line[0] != "#"):
Edit.. Adding a full example.
dic = {}
filename = input("Please Enter the Filename:")
try:
infile = open(filename, 'r')
except IOError:
print("Error Reading File! Program ends here!")
else:
for line in infile:
line = line.strip()
if line and line[0] != "#":
item = line.split(":")
dic["Animal id"] = item[0]
dic["Date"] = item[1]
dic["Station"] = item[2]