Reputation: 11
I'm trying to write a Python 2.7 function that will allow me to type in the name of text file into the pre-made GUI which will open the text file and then pass on the file name as the base for other functions (i.e. count characters) to read that file. I wrote the function before I was given the GUI and now I'm having issue with global variable.
def OpenFile(filename):
try:
rfile = open(filename, "r") #please type the file as a string
except IOError:
print ("File Not Found")
else:
print ("File Opened")
This is what I wrote and I'm not sure where to go from there cause the function is supposed to open the file and prints either of the messages accordingly. I've been trying to find the solution but I'm really struggling.
Upvotes: 1
Views: 1099
Reputation: 5434
The function accepts a file path input and returns the lines in the file and prints 'File Success'
. The functions returns f.readlines
which is basically a list of all the lines in the file.
def get(filename):
try:
with open(filename, "r") as f:
print('File Success')
return f.readlines()
except IOError:
print ("File Not Found")
fname = input("Please insert file path")
contents = get(fname)
I also edited the code to have the input()
outside which improves testability.
Upvotes: 3