Python File Open

Open a file on the server

Assuming we have the following files, located in the same folder as Python:

demofile.txt

Hello! Welcome to demofile.txt
This file is for testing purposes.
Good Luck!

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

open() The function returns a file object, which has a read() The method is used to read the content of the file:

Instance

f = open("demofile.txt", "r")
print(f.read())

Run Instance

Read only a part of the file

By default,read() The method returns the entire text, but you can also specify the number of characters to return:

Instance

Returns the first five characters of the file:

f = open("demofile.txt", "r")
print(f.read(5))

Run Instance

Read Line

You can use readline() The method returns a line:

Instance

Read a line from the file:

f = open("demofile.txt", "r")
print(f.readline())

Run Instance

Through two calls readline()You can read the first two lines:

Instance

Read two lines from the file:

f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())

Run Instance

By traversing the lines in the file through a loop, you can read the entire file line by line:

Instance

Traverse the file line by line:

f = open("demofile.txt", "r")
for x in f:
  print(x)

Run Instance

Close File

It is a good habit to always close the file after completion.

Instance

Close the file after completion:

f = open("demofile.txt", "r")
print(f.readline())
f.close()

Run Instance

Note:In some cases, due to buffering, you should always close the file, and changes made to the file before closing may not be displayed.