B.Tech Students: Apply for Live Programming Internship C, C++, Java, Python ,Web page Designing, PHP Read File in Python | LiveCodeProgramming

Reading Files in Python

Python provides built-in functions to read data from files. We use open() function with reading mode 'r'.

Python में file से data पढ़ने के लिए open() function और reading mode 'r' का उपयोग होता है।

Example 1: Read Entire File

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

Output:

Hello World!
Welcome to Python file reading.

This reads the entire file content at once.

यह पूरे file का content एक बार में पढ़ता है।

Example 2: Read One Line

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

Output:

Hello World!

This reads only the first line.

यह सिर्फ पहली line पढ़ता है।

Example 3: Read Line by Line

f = open("data.txt", "r")
for line in f:
    print(line.strip())
f.close()

Output:

Hello World!
Welcome to Python file reading.

Reads file line by line using a loop.

file को line by line loop से पढ़ता है।

Example 4: Using readlines()

f = open("data.txt", "r")
lines = f.readlines()
for line in lines:
    print(line.strip())
f.close()

Output:

Hello World!
Welcome to Python file reading.

Reads all lines into a list and prints them.

सभी lines को list में लेकर print किया गया है।