-1

I'm trying to read a file on a specific path with with open method. Normally I do this with no problem, but right now there is a txt file on a specific path and Python raising FileNotFoundError. I formatted the pc today, I don't know the problem is about this or not.

I added Python to path. Version is 3.5. I tried these lines at the beginning of file;

#!/usr/bin/env
import os

#!/usr/bin/env python
import os

#!/usr/bin/env python3
import os

none of this worked. Still got the error. How can I fix this error? Searched questions about this problem but there are no answer for me.

UPDATE AFTER COMMENTS

Full traceback is:

`File "C:\Users\windows\Desktop\go.py", line 4, in <module>
    with open ("file") as f:
FileNotFoundError: [Errno 2] No such file or directory: 'file'`

I'm trying to open this file with these codes;

with open ("file") as f:
    t = f.readlines()
print (t)

The file is on the Desktop.

GLHF
  • 3,835
  • 10
  • 38
  • 83
  • 2
    Did you pass the full path? Also make sure to use raw strings or something equivalent. – Padraic Cunningham Feb 23 '16 at 21:51
  • Well, you seem to think the desktop is the problem - so test that. Put the file in any other ('regular') path and run your code. Does it work? Then it is the desktop. Does it not? Then remove all references to "desktop" from your question ... – Jongware Feb 23 '16 at 21:52
  • 1
    The shegang (`#!/usr/bin/env python3`) just decides which python to run. It has nothing to do with how an `open` in that program is going to work. You talk about opening a file but don't have an example that fails, which leaves us guessing what your problem is. It would be easier if you posted a small script that doesn't work and the stacktrack. – tdelaney Feb 23 '16 at 22:04
  • ...and tell us how you are running the script. Are you on the command line? What directory are you in? – tdelaney Feb 23 '16 at 22:06
  • Add `print(os.getcwd())` (after `import os`) so we can see where you are when you try to read the file. You seem to use a lot of names for your file, are you literally trying to open "file" when you want "file.txt"? – tdelaney Feb 23 '16 at 22:14
  • @GLHF, is there an actual file called "file" when you `dir C:\Users\windows\Desktop` – Padraic Cunningham Feb 23 '16 at 22:14

2 Answers2

0

Just a guess. When you say "txt" file, do you mean the file has a ".txt" extension. If so, your code should include the extension.

with open ("file.txt") as f:
    t = f.readlines()
    print (t)
0

You need:

file = 'C:\Users\****\Desktop\1.txt'

with open (file) as f: # " inverted commas not required here
    t = f.readlines()
print (t)
Sociopath
  • 13,068
  • 19
  • 47
  • 75
Lalit
  • 1