0

I am trying to simply build a program, which reads another file. When I try to run the code I get the error mentioned in the topic. I've already tried to take the full path, but it wasn't working. Do you have any ideas to solve the problem?

file = open("Text.txt")
vari = file.read()
print(vari)
Tom Ron
  • 5,906
  • 3
  • 22
  • 38
Try_Python
  • 31
  • 1
  • 3
  • Could you show how your file structure looks like? It would be a bit hard without that – Alexander Santos Jun 03 '20 at 16:07
  • 1
    Add a `print(os.path.join(os.getcwd(), 'Text.txt'))` before trying to open the file. That will show you the full path. –  Jun 03 '20 at 16:10

3 Answers3

1

When you're launching from a command line, the current working directory may not be the same as the home directory of your top-level file (i.e., the directory where your program file resides).

If you run it in cmd.exe (Command Prompt), then path to file "Text.txt" will be searched for in the directory currently opened in the Command line. Usually, C:\Users\[user]\ is the default working directory on Windows.

You need to run your program using Python interpreter/Py Laucher, that is usually opened on double click on *.py top-level program file or simply change the current directory in Command prompt with cd <TOP_LEVEL_FILE_DIR>.

Rykov7
  • 11
  • 3
0

You have to add the full path above file = open("Text.txt") line to indicate where this file is located. Adding the full path to the open(/path/to/where/this/text.txt) like an example is required in this case (so even if your main program is not in the same directory as the file you're trying to open, it will still work). There are many examples on SO, that show how this can be achieved.

de_classified
  • 1,927
  • 1
  • 15
  • 19
  • so I have to attach open("C:\Users\xyz\xyz\xyt...\Text.txt") at the beginning? I tried it but I have no idea why its not working – Try_Python Jun 03 '20 at 17:04
  • I think you're code is missing few extra things the approach I suggested is for absolute path, if you the first answer in this [post](https://stackoverflow.com/questions/32470543/open-file-in-another-directory-python), it shows you the absolute way and relative way. Try to see what you may be missing. – de_classified Jun 03 '20 at 17:09
  • I just watched a Youtube tutorial, I did exactly the same things, but it doesn't work – Try_Python Jun 03 '20 at 17:55
-1

Try the following code,

To open the file, use the built-in open() function.

fileLocation = open("C:/Users/Desktop/Text.txt", "r")
vari = fileLocation.read()
print(vari)

"r": read file "w": write file

It will read the file and will display the contents of the file.

Make sure you use the forward slash in the path.