Lists, Tuples, and Statistics Program Try-Except Block Error - python

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.

Related

reading python file and using input

hi as part of my code i need to read a python file but i keep on getting an error :
other options: {'input': 'dutch_training.txt\nenglish_training.txt\ndutch1.txt\ndutch_training.txt\nenglish_training.txt\ndutch_1.txt\n3\n.4\ndutch_training.txt\nenglish_training.txt\nenglish_1.txt\n4\n.3\ndutch_training.txt\nenglish_training.txt\ndutch_2.txt\n8\n.3\nabc\ndef\nexit\n'}
FileNotFoundError(2, 'No such file or directory')
result_code classify_unknown_text_cut testingFailed 1
i serached google and found that i can use :
os.path.abspath
this is my code:
def classify_unknown_text():
a=1
while a==1:
file_1=os.path.abspath(input("Please enter the filename for language 1: "))
file_2=os.path.abspath(input("Please enter the filename for language 2: "))
clssify_file=os.path.abspath(input("Please enter the filename to classify: "))
if clssify_file=="exit":
a+=1
return
if os.path.isfile(file_1)==False or os.path.isfile(file_2)==False or os.path.isfile(clssify_file)==False:
print("File error: some files do not exist.")
else:
max_length_ngram_1=int(input("Please enter the maximal length of the n-gram: "))
threshold_1=float(input("Please enter threshold value between 0 and 0.5: "))
file_for_dict1=open(file_1,"r")
file_for_dict2=open(file_2,"r")
file3_text=open(clssify_file,"r")
text_dict_1=file_for_dict1.read()
text_dic_2=file_for_dict2.read()
text=file3_text.read()
dict1=compute_ngrams_frequency(text_dict_1,max_length_ngram_1)
dict2=compute_ngrams_frequency(text_dic_2,max_length_ngram_1)
result=classify_language(text,dict1,dict2,threshold_1)
if result==1:
print("I believe the text matches the language in"+file_1)
if result==2:
print("I believe the text matches the language in"+file_2)
if result==0:
print("Sorry, I could not figure this one out!")
#classify_unknown_text()
but i still keep on getting the same error and o dont know what ellse can i do ? thank you
If I'm not wrong, os.path.abspath only returns the absolute path in which your file is stored. If you wish to open a file and read it, or even write it, you could do the following:
#Opens file in read mode
file = open("/path/to/your/file", 'r')
If you want to determine the extension of the file to assure only .py files are read, then you could do:
import os
file_extension = os.path.splitext('/path/to/file')[1]
#Check for extension
if(file_extension == '.py'):
file_open = open('/path/to/file')
Don't know if I helped but I hope so!

read and write multiple files separately from the console, python

I have a function which takes one compulsory file and other possible optional file. Currently the function can read and write single file from the user input. But I want to load and write as many files as user enters from the console input. For that, I want to define function for one compulsory filename and other as an optional parameters.
How do I ask users in console input to enter one compulsory file and other all possible optional filename (only if user wants) and read and write them separately in a function without mixing each other. I want to read and also write separately those all entered files.
Basically, I want to load all filenames which were entered by users in console input and write them separately in each new file.
Currently my function loads and read only one file from the user input.
def read_files(filename, *other):
with open(filename, 'rU') as f:
d = json.load(f)
Input for users:
if __name__ == '__main__':
filename = input('Enter your file name:')
#Here I am confused how do I ask the possible number of filename and How
#do i stop when the user enters all filename
other = input('Enter your other file name')
read_files(filename, )
You could hint that q for quit leads to stop adding further filenames:
if __name__ == '__main__':
filename = input('Enter your file name:')
other=[]
while True:
inp = input('Enter your other file name (q for quit)')
if inp == 'q':
break
else:
other.append(inp)
read_files(filename, other)
EDIT: Probably it's even more convenient to stop if nothing was entered, so the while loop would be:
while True:
inp = input('Enter your other file name (press ENTER for quit)')
if inp == '':
break
else:
other.append(inp)

How can I check whether a given file is FASTA?

I am designing a code that requires a .fasta file to be input at one of the early stages. Right now, I am validating the input using this function:
def file_validation(fasta):
while True:
try:
file_name= str(raw_input(fasta))
except IOError:
print("Please give the name of the fasta file that exists in the folder!")
continue
if not(file_name.endswith(".fasta")):
print("Please give the name of the file with the .fasta extension!")
else:
break
return file_name
Now, although this function works fine, there is still some room for error in the sense that a user could potentially maybe input a file that, while having a file name that ends with .fasta, could have some non-.fasta content inside. What could I do to prevent this and let the user know that his/her .fasta file is corrupted?
Why not just parse the file as if it were FASTA and see whether it breaks?
Using biopython, which silently fails by returning an empty generator on non-FASTA files:
from Bio import SeqIO
my_file = "example.csv" # Obviously not FASTA
def is_fasta(filename):
with open(filename, "r") as handle:
fasta = SeqIO.parse(handle, "fasta")
return any(fasta) # False when `fasta` is empty, i.e. wasn't a FASTA file
is_fasta(my_file)
# False

Changing a variable when an error occurs without terminating the program

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)

Check input python so i can close a file?

file=open('ClassA1.txt','a')
file=open('ClassB1.txt','a')
file=open('ClassC1.txt','a')
print('hello welcome to maths 2000')
Class=input('please enter your class '+"\n")
name=input('please enter your name '+"\n")
if Class==(int(input"A1")):
file.close('ClassB1')
file.close('ClassC1')
file.write(name+"/n")
file.close
How do I get it to check user input so it can close the files?
Ok first point :
This line:
file=open('ClassA1.txt','a')
opens file 'ClassA1.txt' for appending, assign the file object to the name file (which eventually shadows the builtin type file but that's not relevant here)
Then the second line:
file=open('ClassB1.txt','a')
opens file 'ClassB1.txt' for appending, assign the file object to the name file, sus replacing the binding to the previously opened file "ClassA1.txt". Since there's no other name referencing this previously opened file, it's lost. In the best case, the underlying file pointer will be closed when the object gets garbage-collected (CPython) but this is NOT garanteed by thye language's specification and another implementation might not free the file pointer correctly.
In all cases you can not access 'ClassA1.txt' anymore at this point.
Now the third line:
file=open('ClassC1.txt','a')
does the same thing - reassigning the name file to a new file object etc.
At this point, you have to possibly opened, possibly not, and in both case unreachable (and possibly already garbage collected) file objects and the name file points to the third one - which means any write operation on file will write to file "ClassC1.txt".
If you want to keep all three files opened, you have to keep references to them, either by binding each to a distinct name, ie:
file1=open('ClassA1.txt','a')
file2=open('ClassB1.txt','a')
file3=open('ClassC1.txt','a')
or by storing them in a list:
files = []
files.append(open('ClassA1.txt','a'))
files.append(open('ClassB1.txt','a'))
files.append(open('ClassC1.txt','a'))
so you can now acces them by index, ie files[0], files[1], files[2]
or in a dict:
files = {}
files["A1"] = open('ClassA1.txt','a')
files["B1"] = open('ClassB1.txt','a')
files["C1"] = open('ClassC1.txt','a')
so you can now acces them by key, ie files["A1"], files["A2"], files["A3"]
BUT : why would you
open three files,
ask the user which file he wants to write to,
close the two other files,
write to the selected file
close it
when you could more simply:
ask the user which file he wants to write to,
open it
write to it
close it
Since your files are named after the class name, you can easily build the filename from the class name:
cls = input("please enter your class\n")
filename = "Class{}.txt".format(cls)
f = open(filename, "a")
f.write("whatever")
f.close()
or even more safely (this will ensure the file WILL be closed whatever happens):
cls = input("please enter your class\n")
filename = "Class{}.txt".format(cls)
with open(filename, "a") as f:
f.write("whatever")
Note that in this case you don't have to call f.close()
A couple other points:
Class=input('please enter your class '+"\n")
=> 'cls' or 'class_', not 'Class' - by convention, capitalized names are for class (in the OO meaning) names.
=> Python is not PHP: 'please enter your class \n' just works
if Class==(int(input"A1"))
I don't know what you expect this line to do, but it sure looks you don't know either... One thing is sure : a string won't be equal to an integer. Never...
file.close('ClassB1')
Have you read the documentation at all ? It's here (well, for a starter at least) : https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files
file.close
You want file.close() here. The parens are NOT optional - if you want to call the method at least.
You're doing a long winded way, you could just open the file after the user gives their answer.
import os
print('hello welcome to maths 2000')
yourClass=input('please enter your class '+"\n")
filename = 'Class{}.txt'.format(yourClass)
name=input('please enter your name '+"\n")
if os.path.exists(filename):
f = open(filename, 'a')
file.write(name+"/n")
file.close()
else:
print ("Class not found")
I just set it up so the input determines the filename it tries to open, and if that file exists it opens it and appends their name.
When you execute these
file=open('ClassA1.txt','a')
file=open('ClassB1.txt','a')
file=open('ClassC1.txt','a')
file variable contains "ClassC1.txt", you are re-assigning the object again and again.
so after whatever check if you execute this:
file.close()
last file will be closed.
Instead I would recommend you first take the input of what file is to be opened and then open that file.
file_name = input("Enter file name")
file = open(file_name, 'a')
#do your work
file.close()
fd = open("Student_info.txt", "a+")
class_info = []
print "Hello, welcome to maths 2000"
class_to_be = raw_input("Please enter your class: ")
name = raw_input("Please enter your name: ")
student = name + " " + class_to_be
class_info.append(student)
print class_info
for students in class_info:
fd.write("%s" %(students))
fd.close()
results:
jester112358#ubuntu:~$ python stackhelp.py
Hello, welcome to maths 2000
Please enter your class: Python-class
Please enter your name: Greenie245
['Greenie245 Python-class']
and writes the content of your list to Student_info.txt
I think it's better to have all the information in one file, but obviously you can have a file for every class if you want.
If you want class for every file, consider using:
for students in class_info:
spl = students.split()
if spl[1] == "A1":
A1=open('ClassA1.txt','a')
A1.write("%s" %(students))
A1.write("\n")
A1.close()
elif ... # add anothor classes here

Categories