0

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()
j0h
  • 1,675
  • 6
  • 27
  • 50
  • 2
    The use of backticks in the `open` call is the problem. You want normal quotes there. Backticks are a deprecated alias for the `repr` function (which called on a string gets you a quoted string which is what you see in your error). – Etan Reisner Nov 20 '14 at 02:22
  • I just tried this: but it didn't work. f = open(repr(fn),'r') am i doing it wrong? – j0h Nov 20 '14 at 02:28
  • 1
    Yes, you misunderstood my comment. `repr` is *incorrect*. You **don't** want it. You want a normal variable. My comment was partially incorrect though. You don't want quotes at all. `fn` is a variable with a string in it. `open(fn, 'r'`). – Etan Reisner Nov 20 '14 at 02:31

3 Answers3

2

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)
Community
  • 1
  • 1
Jim
  • 73
  • 1
  • 7
1

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:]]
Stefan Gruenwald
  • 2,582
  • 24
  • 30
0

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.

Kill Console
  • 1,933
  • 18
  • 15