reading python file and using input - python

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!

Related

Try/Except not running properly when opening files

I am trying to open a file with this Try/Except block but it is going straight to Except and not opening the file.
I've tried opening multiple different files but they are going directly to not being able to open.
import string
fname = input('Enter a file name: ')
try:
fhand = open(fname)
except:
print('File cannot be opened:', fname)
exit()
counts = dict()
L_N=0
for line in fhand:
line= line.rstrip()
line = line.translate(line.maketrans(' ', ' ',string.punctuation))
line = line.lower()
words = line.split()
L_N+=1
for word in words:
if word not in counts:
counts[word]= [L_N]
else:
if L_N not in counts[word]:
counts[word].append(L_N)
for h in range(len(counts)):
print(counts)
out_file = open('word_index.txt', 'w')
out_file.write('Text file being analyzed is: '+str(fname)+ '\n\n')
out.file_close()
I would like the output to read a specific file and count the created dictionary
make sure you are inputting quotes for your filename ("myfile.txt") if using python 2.7. if python3, quotes are not required.
make sure your input is using absolute path to the file, or make sure the file exists in the same place you are running the python program.
for example,
if your program and current working directory is in ~/code/
and you enter: 'myfile.txt', 'myfile.txt' must exist in ~/code/
however, its best you provide the absolute path to your input file such as
/home/user/myfile.txt
then your script will work 100% of the time, no matter what directory you call your script from.

Basic Python Programming - writing data in a file

I am just a beginner to programming and below is the code that I have written in python to save and edit a file but every time I run the programme it erases the previous save data, so I am confused why it's happening?
filename = raw_input("Please enter the file name to open it:\n")
doc = open (filename,'w')
print doc.read
text_input = raw_input("Please enter the data you want to enter in file:\n")
if text_input == "":
print "no input closing the programme."
else :
doc.write(text_input)
doc.close()
print "Printing the file:\n"
print doc.read
cl_file = raw_input("do you want to truncate file(y/n): ")
if cl_file == "y":
doc.truncate()
else :
print "Wrong input closing notepad"
exit()
You are opening the file in write mode, which truncates the file before writing to it. Instead of using open(filename, 'w') use open(filename, 'a'). The 'a' value tells the open function to use append mode so that writes to the file are added to the end of any existing content.

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)

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

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.

Opening a file with a name error

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)

Categories