This is my basic code:
fname = input("What is the name of the file to be opened")
file = open(fname+".txt", "r")
message = str(file.read())
file.close()
What I want to do is essentially make sure the file the program is attempting to open exists and I was wondering if it was possible to write code that tries to open the file and when it discovers the file doesn't exist tells the user to enter a valid file name rather then terminating the program showing an error.
I was thinking whether there was something that checked if the code returned an error and if it did maybe made an variable equal to invalid which an if statement then reads telling the user the issue before asking the user to enter another file name.
Pseudocode:
fname = input("What is the name of the file to be opened")
file = open(fname+".txt", "r")
message = str(file.read())
file.close()
if fname returns an error:
Valid = invalid
while valid == invalid:
print("Please enter a valid file name")
fname = input("What is the name of the file to be opened")
if fname returns an error:
Valid = invalid
etc.
I guess the idea is that you want to loop through until your user enters a valid file name. Try this:
import os
def get_file_name():
fname = input('Please enter a file name: ')
if not os.path.isfile(fname+".txt"):
print('Sorry ', fname, '.txt is not a valid filename')
get_file_name()
else:
return fname
file_name = get_file_name()
Going by the rule Asking for forgiveness is better then permission
And using context-manager and while loop
Code :
while True: #Creates an infinite loop
try:
fname = input("What is the name of the file to be opened")
with open(fname+".txt", "r") as file_in:
message = str(file_in.read())
break #This will exist the infinite loop
except (OSError, IOError) as e:
print "{} not_available Try Again ".format(fname)
Related
file = input("Enter file name:")
try:
fhand = open(file,'r')
except:
print("File not found")
quit() # Error: name 'quit' is not defined
count = 0
for line in fhand:
line =line.strip()
if line.startswith('Subject'):
count+=1
print('There were,',count,'subject lines in ',file)
This error should not occur. I am confused to heights what am I doing wrong here. i get the error 'name 'quit' is not defined'. Which should not come.
quit() and exit() rely on the site module, and, to my knowledge, they're designed for being used in interactive mode and not in actual programs or production code.
Instead, I'd recommend making your program look more like this:
file = input("Enter file name:")
try:
fhand = open(file,'r')
count = 0
for line in fhand:
line =line.strip()
if line.startswith('Subject'):
count+=1
fhand.close()
print('There were,',count,'subject lines in ',file)
except FileNotFoundError:
print("File not found")
You also may want to read the file immediately and close it sooner.
I am trying to make a simple bruteforcer for rar files. My code is...
import rarfile
file = input("Password List Directory: ")
rarFile = input("Rar File: ")
passwordList = open(file,"r")
for i in passwordList:
try :
rarfile.read(rarFile, psw=i)
print('[+] Password Found: '+i)
except Exception as e:
print('[-] '+i+' is not a password ')
passwordList.close()
I think this has to do with my use of the module, because when I input a password list that I am 10000% sure contains the password to the rarFile, it prints the exception.
The real problem here is that you are catching all exceptions, not just the one you want. So use except rarfile.PasswordRequired: That will show you that the error is not a missing password. Instead there is no function read in the rarfile module.
Have a look at some Documentation. Rar encryption is per file, not per archive.
You need to create a object from the RarFile class and try the password on each file in the archive. (or just the first if you know that is encrypted)
import rarfile
file = input("Password List Directory: ")
rarFilename = input("Rar File: ")
rf = rarfile.RarFile(rarFilename)
passwordList = open(file,"r")
first_file = next(rf.infolist)
for i in passwordList:
password = i.rstrip()
try:
rf.open(first_file, psw=password)
print(password, "found")
except rarfile.PasswordRequired:
print(password,"is not a password")
When you open and read lines from a file, the "new line" character is kept
at the end of the line. This needs to be stripped from each line.
for i in passwordList:
password = i.rstrip()
try :
rarfile.read(rarFile, psw=password)
print('[+] Password Found: '+password)
I am making a program that encrypts the contents of a file into cipher text. My problem is that when my program asks the user to input the name of the file they want to load and the user doesn't give a valid response, then the "FileNotFoundError:" shows up. I want my program to have a function where if the user doesnt give a valid response, the program will keep telling the user to retry.
def EncryptCode():
encryptFileLoad = input("Name the file and directory you want to load with the ending '.txt':\n")
with open (encryptFileLoad,mode="r",encoding="utf=8") as encrypt_file:
encryptFile = encrypt_file.read()
I get an error like this:
Traceback (most recent call last):
File "C:\...
FileNotFoundError: [Errno 2] No such file or directory: 'test.txt'
i have tried doing something like this:
def EncryptCode():
...
try:
...
except FileNotFoundError:
return EncryptCode
What about
def EncryptCode():
file_not_found = True
while(file_not_found):
try:
encryptFileLoad = input("Name the file and directory you want to load with the ending '.txt':\n")
file_not_found = False
except FileNotFoundError:
print('that didnt work! try again')
with open (encryptFileLoad,mode="r",encoding="utf=8") as encrypt_file:
encryptFile = encrypt_file.read()
You almost made it. Check http://www.python-course.eu/recursive_functions.php It should be something like this:
def EncryptCode():
try:
encryptFileLoad = input("Name the file and directory you want to load with the ending '.txt':\n")
with open(encryptFileLoad,mode="r",encoding="utf=8") as encrypt_file:
encryptFile = encrypt_file.read()
return encryptFile
except FileNotFoundError:
print('File not found. Input correct filename')
return EncryptCode()
Or you can use while loop to ask user input correct filename like:
while True:
try:
encryptFileLoad = input("Name the file and directory you want to load with the ending '.txt':\n")
with open (encryptFileLoad,mode="r",encoding="utf=8") as encrypt_file:
encryptFile = encrypt_file.read()
break
except FileNotFoundError:
print('File not found. Input correct filename')
I am working on a Lists, Tuples, and Statistics Program for my intro class, and am having some difficulty with a try-except block. The program we are supposed to make is supposed to ask for the user to name a file to input, and then give some information about the numbers in that file. I have all of the information displays working correctly, but can't write the try-except block. The program needs to accept only the file name "new_numbers.txt" and nothing else.
Here is the top portion of my code:
def main():
#Get the name of the file from the user
while(True):
try:
input("Enter the name of the file you would like to open: ")
except ValueError:
print("That file does not exist. Please enter a valid file.")
break
You need to assign the value from input, and try to open it to see if the file in question is around...:
def main():
#Get the name of the file from the user
while(True):
try:
fn = input('Enter the name of the file you would like to open: ')
f = open(fn)
except IOError:
print('File {} does not exist. Please enter a valid file.'.format(fn))
else:
break
Also note that you should break only when there is no more error; and in that case the open file object is ready as variable f.
I am trying to build a function that asks the user to input the name of a file, opens the file, reads its contents, prints the contents of the file on the screen, and closes the file. If no such file exists, it's okay if the script crashes. When I run the function, it gives me: NameError: name 'myInput' is not defined, and I'm not sure how to fix it.
Here is what I have so far:
print(input('Please enter the name of a file that you want to open.' + myInput))
with open(r"C:\Python32\getty.txt", 'r') as infile:
data = infile.read()
print(data)
Help if you can..
myInput is an undefined variable, and I can't fathom what you had in mind by using it.
Maybe where you show the code...:
print(input('Please enter the name of a file that you want to open.' + myInput))
with open(r"C:\Python32\getty.txt", 'r') as infile:
you actually meant something very different, e.g like...:
myInput = input('Please enter the name of a file that you want to open.')
with open(myInput, 'r') as infile:
...?
In your first line, you have:
print(input('Please enter the name of a file that you want to open.' + myInput))
do you have myInput defined? You need to define it. If you don't have it defined before that line, your script will crash.
This can be gleaned from your helpful error message:
NameError: name 'myInput' is not defined
Which means that the variable myInput is not defined, so the compiler doesn't know what to put there.
I think something like this would solve your problem
fileName = raw_input("Please enter the name of a file that you want to open. ")
fileObject = open(fileName, "r")
fileText = fileObject.read()
print(fileText)