Cannot stop program from crashing with wrong file entered by user - python

I am creating a program which asks the user to choose a file to run within the program but I can't stop the program from crashing when a file name that does not exist is entered. I have tried try statements and for loops but they have all given an error. The code I have for choosing the file is below:
data = []
print "Welcome to the program!"
chosen = raw_input("Please choose a file name to use with the program:")
for line in open(chosen):
our_data = line.split(",")
data.append(our_data)

Add an exception:
data = []
print "Welcome to the program!"
chosen = raw_input("Please choose a file name to use with the program:")
try:
for line in open(chosen):
our_data = line.split(",")
data.append(our_data)
except IOError:
print('File does not exist!')

Without using an exception you can simply check if the file exists and if not ask for it again.
import os.path
data = []
print "Welcome to the program!"
chosen='not-a-file'
while not os.path.isfile(chosen):
if chosen != 'not-a-file':
print("File does not exist!")
chosen = raw_input("Please choose a file name to use with the program:")
for line in open(chosen):
our_data = line.split(",")
data.append(our_data)

RTM
import sys
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except IOError as e:
print "I/O error({0}): {1}".format(e.errno, e.strerror)
except ValueError:
print "Could not convert data to an integer."
except:
print "Unexpected error:", sys.exc_info()[0]
raise

Related

Python Bruteforcing zip file cannot assign to function call

I am learning how to access a zip file with python BruteForcing. but I am facing a problem when I do that in the zipF in line 11
that is the exception: cannot assign to function call.
import zipfile
zipF = zipfile.ZipFile
zipName = input("File path : ")
passwordFile = open("14MillionPass.txt","r")
for passw in passwordFile.readlines():
ps = str(int(passw))
ps = ps.encode()
try:
with zipF.ZipFile(zipName) as myzip(): #the error is here
myzip.extractAll(pwd = ps)
print("Password found \n -> {0} is {1} password".format(ps,zipName))
break
except:
print("password not found")
Thanks in advance
You can't use a break inside a try-catch statement. also, you try to assign a function to the file handler. You can use exit(0) instead of break
try:
with zipfile.ZipFile(zipName) as myzip:
myzip.extractAll(pwd = ps)
print("Password found \n -> {0} is {1} password".format(ps,zipName))
exit(0) # successful exit
except:
print("password not found")
And you have broken indentation in your program, maybe this is want you want
import zipfile
zipName = input("File path : ")
passwordFile = open("14MillionPass.txt","r")
for passw in passwordFile.readlines():
ps = str(int(passw))
ps = ps.encode()
try:
with zipfile.ZipFile(zipName) as myzip:
myzip.extractAll(pwd = ps)
print("Password found \n -> {0} is {1} password".format(ps,zipName))
break
except:
print("password not found")

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

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.

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.

Python code to ignore errors

I have a code that stops running each time there is an error.
Is there a way to add a code to the script which will ignore all errors and keep running the script until completion?
Below is the code:
import sys
import tldextract
def main(argv):
in_file = argv[1]
f = open(in_file,'r')
urlList = f.readlines()
f.close()
destList = []
for i in urlList:
print i
str0 = i
for ch in ['\n','\r']:
if ch in str0:
str0 = str0.replace(ch,'')
str1 = str(tldextract.extract(str0))
str2 = i.replace('\n','') + str1.replace("ExtractResult",":")+'\n'
destList.append(str2)
f = open('destFile.txt','w')
for i in destList:
f.write(i)
f.close()
print "Completed successfully:"
if __name__== "__main__":
main(sys.argv)
Many thanks
You should always 'try' to open files. This way you can manage exceptions, if the file does not exist for example. Take a loot at Python Tutorial Exeption Handling
import sys
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except IOError as e:
print "I/O error({0}): {1}".format(e.errno, e.strerror)
except ValueError:
print "Could not convert data to an integer."
except:
print "Unexpected error:", sys.exc_info()[0]
raise
or
for arg in sys.argv[1:]:
try:
f = open(arg, 'r')
except IOError:
print 'cannot open', arg
else:
print arg, 'has', len(f.readlines()), 'lines'
f.close()
Do not(!) just 'pass' in the exception block. This will(!) make you fall on your face even harder.
Where ever your error(s) is happening you can wrap it in a try/except block
for i in loop:
try:
code goes here...
except:
pass

Categories

Resources