لَآ إِلَـٰهَ إِلَّا هُوَ
LA ILAHA ILLA HU
Allah, Your Lord There Is No Deity Except Him.

Python Data Science File Handling In Python: Open a File on the Server

We have kept one more file at the same location.

Example 2: Open a File on the Server.

Code

f = open("example2.txt", "r")

print(f.read())

the output will be

Hello! Welcome to LFPPL.COM

This file is for testing purposes.

Good Luck!

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

The open() function returns a file object, which has a read() method for reading the content of the file.

Example 3

Code

f = open("C:\\Users\\Desktop\\File-Handling\\example3.txt")

print(f.read())

the output will be

Hello! Welcome to LFPPL.COM

This file is for testing purposes.

This file is located on a different location in a folder name File-Handling.

Good Luck!

Read Only Parts of the File

By default the read() method returns the whole text.
You can also specify how many characters you want to return.

Example 4: Return the 50 first characters of the file.

Code

f = open("example.txt", "r")

print(f.read(50))

the output will be

ILLUSTRATION

This is Line 1.

This is Line 2.

This

Read Lines

You can return one line by using the readline() method.

Example 5: Read one line of the file.

Code

f = open("example.txt", "r")

print(f.readline())

the output will be

ILLUSTRATION

Note: By calling readline() two times, you can read the two first lines.

Example 6: Read two line of the file.

Code

f = open("example.txt", "r")

print(f.readline())

print(f.readline())

the output will be

ILLUSTRATION

This is Line 2.

Looping Through Lines

You can read the whole file,
line by line by looping through the lines of the file.

Example 7: Loop through the file line by line.

Code

f = open("example.txt", "r")

for x in f:

print(x)

the output will be

ILLUSTRATION

This is Line 2.

This is Line 3.

This is Line 4.

This is Line 5.

Closing the File

A good practice to close the file when you are done.

Example 8: Close the file once you are finished.

Code

f = open("example.txt", "r")

print(f.readline())

f.close()

the output will be

ILLUSTRATION

Note: You should always close your files.

in some cases, due to buffering,
changes made to a file may not show until you close the file.