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

Python File Methods

Python provides various built-in methods to read, write and manage files. Let's look at them:

Python में file को read, write और manage करने के लिए कई built-in methods होते हैं। नीचे कुछ मुख्य methods दिए गए हैं:

1. read()

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

Reads the entire content of the file.

यह file का पूरा content पढ़ता है।

2. readline()

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

Reads one line at a time.

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

3. readlines()

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

Returns all lines as a list.

यह सभी lines को list के रूप में return करता है।

4. write()

f = open("newfile.txt", "w")
f.write("Welcome to LiveCodeProgramming!")
f.close()

Writes a single string to file.

यह एक string file में लिखता है।

5. writelines()

lines = ["Hello\n", "Welcome\n", "Python File Handling\n"]
f = open("multiple.txt", "w")
f.writelines(lines)
f.close()

Writes multiple lines (strings) to the file.

यह एक साथ कई lines को file में लिखता है।

6. close()

Always use close() to safely close the file after reading/writing.

File को safely बंद करने के लिए हमेशा close() method का use करें।