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')
Related
I'm trying to open a file named alldata.numbers using this code but I get the error:
FileNotFoundError: [Errno 2] No such file or directory: 'alldata.numbers'
This is my code:
def main():
# Asks user for filename
inName = input("What is the filename? ")
# Open file and read first line
inFile = open(inName, "r")
for i in range():
data = inFile.readline()
print(data)
return
main()
The file alldata.numbers is on my desktop with my saved code. How can I fix this so I can open any file?
changed the code to:
def main():
# Asks user for filename
inName = input("What is the filename for input? ")
# Open file and read first line
inFile = open(inName, "r")
for line in inFile:
inFile = inFile.readline()
print(inFile)
return
main()
Works now :)
I am trying to write to a file that doesn't exist. I was told that when using "w" it would create the file if it doesn't exist. However this did not work and returned an error. I then added a line using "x" to create the file. This still returned an error.
Here is the error:
Traceback (most recent call last):
File "C:\Users\brain\Documents\Python projects\Calendar\Calendar.py", line 22, in <module>
day = open(today+".txt", "x")
FileNotFoundError: [Errno 2] No such file or directory: '6/11/2021.txt'
Here is the code:
print("You do not have any reminders for today.")
print("Would you like to make some?")
newtoday = input().lower()
if newtoday == "yes":
filename = open("filenames.txt", "w")
filename.write(today)
day = open(today+".txt", "x")
day.close()
day = open(today+".txt", "w")
print("What would you like the title of the reminder to be?")
title = input()
print("Add any extra details below e.g. time, place.")
det = input()
day.write(title+": "+det, "(x)")
filename.close()
day.close()
Since today is a string containing / characters, day = open(today+".txt", "x") will read this string as a path to create the file in.
Your today variable contains 6/11/2021, so it will look for the directory structure 6/11 and in that folder it will try to create the file 2021.txt. Since he can't find those directories, the instruction will fail. You can try to format your file name 6-11-2021.txt. If you do want to use the directories, you can parse today and create directories using os.mkdir
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.
recently i started learning Python and encountered a problem i can`t find an answer to.
Idea of the program is to ask for username, load a dictionary from JSON file, and if the name is in the dictionary - print the users favourite number.
The code, that loads the JSON file looks like this:
import json
fav_numbers = {}
filename = 'numbers.JSON'
name = input('Hi, what`s your name? ')
try:
with open(filename) as f_obj:
fav_numbers = json.load(f_obj)
except FileNotFoundError:
pass
if name in fav_numbers.keys():
print('Hi {}, your fav number is {}, right?'.format(name, fav_numbers[name]))
else:
number = input('Hi {}, what`s your favourte number? '.format(name))
fav_numbers[name] = number
with open(filename, 'w') as f_obj:
json.dump(fav_numbers, filename)
Still, as i try to run it, it crashes, telling me:
Exception has occurred: FileNotFoundError
[Errno 2] No such file or directory: 'numbers.JSON'
File "/home/niedzwiedx/Dokumenty/Python/ulubionejson.py", line 22, in <module>
with open(filename) as f_obj:
What i`m doing wrong to catch the exception? (Already tried changing the FileNotFoundError to OSError or IOError)
The error comes from you last line, outside of your try/except
with open(filename, 'w') as f_obj:
json.dump(fav_numbers, filename)
filename is a string, not a file.
You have to use
with open(filename, 'w') as f_obj:
json.dump(fav_numbers, f_obj)
For additional safety, you can surround this part with try/except too
try:
with open(filename, 'w') as f_obj:
json.dump(fav_numbers, f_obj)
except (FileNotFoundError, PremissionError):
print("Impossible to create JSON file to save data")
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)