j0h
j0h

Reputation: 1784

Read file-names with extensions into python

I am trying to read a filename that has a period in it, into this simple program.. files like "test" work, while test.txt fail. I kinda see why. when I type in "test.txt", only "test" appears. when I use quotes, I get:

 IOError: [Errno 2] No such file or directory: "'test.txt'"

is there a simple way I can read file names that have things like extensions?

   #!/usr/bin/python
   #File Attributes
   fn=input("Enter file Name: ")
   print (fn) #added so i know why its failing.
   f = open(`fn`,'r')
   lines = f.read()
   print(lines)
   f.close()

Upvotes: 0

Views: 170

Answers (3)

Stefan Gruenwald
Stefan Gruenwald

Reputation: 2640

I would do it the following way:

from os.path import dirname

lines = sorted([line.strip().split(" ") for line in open(dirname(__file__) + "/test.txt","r")], key=lambda x: x[1], reverse=True)

print [x[0] for x in lines[:3]]
print [x[0] for x in lines[3:]]

Upvotes: 1

Jim
Jim

Reputation: 73

Using the with...as method as stated in this post: What's the advantage of using 'with .. as' statement in Python? seems to resolve the issue.

Your final code in python3 would look like:

#!/usr/bin/python
#File Attributes
fn = input("Enter file Name: ")
with open(fn, 'r') as f:
    lines = f.read()
    print(lines)

In python2 *input("")** is replaced by raw_input(""):

#!/usr/bin/python
#File Attributes
fn = raw_input("Enter file Name: ")
with open(fn, 'r') as f:
    lines = f.read()
    print(lines)

Upvotes: 2

Kill Console
Kill Console

Reputation: 2023

You use the input function, this built_in function need a valid python input, so you can try this:

r'test.txt'

But you have to make sure that the test.txt is a valid path. I just try your code, I just change the open function to:

f = open(fn,'r')

and input like this:

r'C:\Users\Leo\Desktop\test.txt'

it works fine.

Upvotes: 0

Related Questions