V. Sel
V. Sel

Reputation: 13

How to properly open a file in python and have the text contents printed out

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'

Upvotes: 1

Views: 43

Answers (2)

Adi219
Adi219

Reputation: 4814

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.

Upvotes: 2

Jones1220
Jones1220

Reputation: 786

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.

Upvotes: 1

Related Questions