1

I am trying to open an existing file called sun_og.text. Below is my code. I want what is written in the file to print out in my terminal.

f = open("sun_og.txt", "r")
file_contents = f.read()
print (file_contents)
file.close()

But I keep getting this error message

FileNotFoundError: [Errno 2] No such file or directory: 'sun_og.txt'
3
  • 2
    The error looks quite clear, try providing the full path Commented Aug 9, 2018 at 9:51
  • I am very new to coding, can you explain what you mean @gogaz ? Commented Aug 9, 2018 at 9:54
  • Just get the path of the file (it'll look like "C://Windows/User/Me/Documents/..." for example on my computer (as I have a Windows laptop)) Commented Aug 9, 2018 at 9:57

2 Answers 2

2

It's likely that your script isn't located in the same directory as the text file, which is why this error is being raised.

To fix this, try providing an absolute/relative filepath.

Also, when handling files, it's better to use with as it automatically closes the file for you.

So try this:

with open("your_path/sun_og.txt", "r") as f:
    file_contents = f.read() ## You only need this line if you're going to use the file contents elsewhere in the code
    print(file_contents) ## Otherwise, you could remove the line above and replace this line with print(f.read())

Alternatively, you could use the os module as you can use its chdir function to relocate to another directory (in this case, the directory of your text file). See @Jones1200's answer for more information.

Sign up to request clarification or add additional context in comments.

1 Comment

@V.Sel No problem :)
1

You can use the os module to go to the directory, where your text-file is.

import os

directory_of_text = r'Your/Directory/with/text_file'
os.chdir(directory_of_text)

use your code after that and it should work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.