Reputation: 1
I am trying to open a file on python using this code:
fileName=input('Please enter the file name: ')
file=open(fileName,'r')
I get asked to enter the file name which is grid.txt, I type that in but nothing appears, am I doing something wrong, if so what am I doing wrong and what is the solution.
Thanks.
Upvotes: 0
Views: 434
Reputation: 1
Add following print stmt to see detail about file
with open(fileName) as file:
print("Name of the file: ", file.name)
print("Closed or not : ", file.closed)
print("Opening mode : ", file.mode)
print("Softspace flag : ", file.softspace)
print("file read:", file.read())
Upvotes: 0
Reputation: 5384
You can also use with
fileName = input('Please enter the file name: ')
with open(fileName, 'r') as fd:
for line in fd:
print(line.strip())
This will close the file when it's done as well
Upvotes: 1
Reputation: 2656
file.open()
doesn't open a file in a text editor (which is what I'm assuming you thought it does).
Instead, it prepares the data for access via python.
As stated in the comment below your Question already: you have to do something with the file.
Try:
with open(fileName) as f:
print(f.read())
Read up on the documentation for open() here.
Also, using the with open()
statement will improve your codes readability, as well as handling the closing of the file for you.
.
Upvotes: 0
Reputation: 343
You have successfully created the file object, however you have only stated that it exists.
All you need is to print it afterwards, here's an example below :
f = open('workfile', 'r')
print f.read()
Alternatively f.readline()
will read the next line each time it is called, and by convention f.close()
should be called to close the file after you are done reading/writing to it.
Upvotes: 1
Reputation: 1913
Here's some code doing what you are looking for:
fileName=input('Please enter the file name: ')
f=open(fileName,'r')
print(f.read())
f.close()
Upvotes: 1