Catch all errors when trying to open a txt file - python

I'd like to catch all errors when trying to open a txt file that doesn't even exist.
This is my code block:
def read_credentials(filename):
try:
with open(txt_file) as file:
lines = file.readlines()
username = lines[0].replace(" ", "").replace("\n", "")
password = lines[1].replace(" ", "").replace("\n", "")
return username, password
except IOError:
print("oops")
read_credentials('login.txt')
But I still get the following error:
username, password = read_credentials('login.txt')
TypeError: cannot unpack non-iterable NoneType object
How can I catch this?

I fixed it by wrapping the called function in an if-block:
if read_credentials('login.txt') is None:
print('oops')
else:
print('rest of code')

Related

using open() to read file and then using specific lines in if statement python

I'm working on a login system in python atm.
I got so far that I can register a user and create a .txt file with the username and password in two different lines.
textfile
But when it comes to the login system I've run into a problem. I can read the textfile, but when I'm using these two different lines in an if statement using:
try:
#usr is the username given in the login process by the user(the name of the
#created file is always the name of the user)
data = open(usr + ".txt", "r")
l = data.readlines()
#l[0] is reading the first line of code and the iam comparing
#them to the username and password given by the user
if l[0] == usr and l[1] == pss:
print('LOGED IN')
else:
print('WRONG')
except Exception as e:
print('Error reading file')
I am using the latest version of python and I am running on LinuxPopOs
my whole code:
import time
print("LOGIN -> 1")
print("Register -> 2")
print("")
select_ = input("")
if select_ == '2':
print("Username:")
usernamee = input()
print("Password:")
passworde = input()
print("Type ""y"" to register or ""n"" to cancel")
forward = input("")
if forward == 'y':
#creating database
data = open(usernamee + ".txt", "w")
data.write(usernamee + "\n")
data.write(passworde)
data.close()
else:
print('closing...')
time.sleep(2)
exit(0)
elif select_ == '1':
print("LOGIN:")
usr = input("Username:")
pss = input("Password:")
try:
#usr is the username given in the login process by the user
data = open(usr + ".txt", "r")
l = data.readlines()
#l[0] is reading the first line of code and the iam comparing
#them to the username and password given by the user
if l[0] == usr and l[1] == pss:
print('LOGED IN')
else:
print('WRONG')
except Exception as e:
print('Error reading file')
else:
print(select_ + "is not valid")
Thanks
The problem appears to be that white space and/or newline characters aren't being stripped from the strings read by readline. Changing the if statement to strip trailing characters should rectify that, e.g. if l[0].rstrip() == usr and l[1].rstrip() == pss:

How can i add the functions try/except in this code?

I'm still creating this code where via a dictionary attack i find a password, inserted by the user. However I would insert some controls in the input of the file's source (ex. when I type the source of a file that doesn't exist) and when I open a file but inside there isn't a word that match with the password typed by the user. My mind tell me that I can use istructions as "If, Else, Elif" but other programmers tell me that i could use the try except instructions.
This is the code:
"""
This Code takes as input a password entered by the user and attempts a dictionary attack on the password.
"""
def dictionary_attack(pass_to_be_hacked, source_file):
try:
txt_file = open(source_file , "r")
for line in txt_file:
new_line = line.strip('\n')
if new_line == pass_to_be_hacked:
print "\nThe password that you typed is : " + new_line + "\n"
except(
print "Please, type a password: "
password_target = raw_input()
print "\nGood, now type the source of the file containing the words used for the attack: "
source_file = raw_input("\n")
dictionary_attack(password_target, source_file)
You can put this as your "File does not exist" exception and after you open the existing file you can but an if statement to check if anything exist inside the file in your way:
"""
This Code takes as input a password entered by the user and attempts a dictionary attack on the password.
"""
def dictionary_attack(pass_to_be_hacked, source_file):
try:
txt_file = open(source_file , "r")
if os.stat( txt_file).st_size > 0: #check if file is empty
for line in txt_file:
new_line = line.strip('\n')
if new_line == pass_to_be_hacked:
print("\nThe password that you typed is : " + new_line + "\n")
else:
print "Empty file!"
except IOError:
print "Error: File not found!"
print "Please, type a password: "
password_target = raw_input()
print "\nGood, now type the source of the file containing the words used for the attack: "
source_file = raw_input("\n")
dictionary_attack(password_target, source_file)

Cannot stop program from crashing with wrong file entered by user

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

Getting exception syntax error

I wrote a function. Now I keep getting syntax errors within the try statement. I don't know if its the code I wrote or the try statement
Function:
def connector (links):
for links in infile:
avenues = links.rstrip()
words = []
dct = {}
cord = []
There is more to the code but the error keeps occurring in the try statement, where it says except, any ideas?
try:
infile = open("routes.txt", "r")
links = inf.readlines()
Connector(links)
except LookupError as exceptObj:
print("Error:", str(exceptObj))
connector should be lowercase
You indented wrong
try:
infile = open("routes.txt", "r")
links = inf.readlines()
connector(links)
except LookupError as exceptObj:
print("Error:", str(exceptObj))

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