DEV Community

Mr #1738
Mr #1738

Posted on

Opening files in python with open() function.

First, create a file named hello.txt and add the text below:
"continue coding in Python Mzee." Next, we need to create another file called demo.py which will contain code that will read text from hello.txt file:

f = open("hello.txt","r")
print(f.read())
Enter fullscreen mode Exit fullscreen mode

when demop.py is run we the text, output

continue coding in python mzee
Enter fullscreen mode Exit fullscreen mode

in summary f = open("hello.txt", "r"): opens a file named "hello.txt" in read mode ("r") and creates a file object called f that you can use to interact with the file.

print(f.read()): reads the contents of the file represented by the f file object and then prints those contents to the console or screen. The read() method reads the entire content of the file as a single string and then print() displays it.

Top comments (0)