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

Writing Files in Python

To write to a file in Python, we use the open() function with mode "w" or "a". The write() and writelines() methods help save content to the file.

Python में file में लिखने के लिए open() function का use "w" या "a" mode के साथ किया जाता है। write() और writelines() से data लिखा जाता है।

Example 1: Write Single Line

f = open("output.txt", "w")
f.write("Hello from Python!\n")
f.close()

This creates a file and writes a line to it. If file already exists, it will be overwritten.

यह एक file बनाता है और एक लाइन लिखता है। अगर file पहले से है, तो overwrite होगी।

Example 2: Write Multiple Lines

f = open("output.txt", "w")
f.write("Line 1\n")
f.write("Line 2\n")
f.write("Line 3\n")
f.close()

Each line is written using write() separately.

हर लाइन write() से अलग-अलग लिखी गई है।

Example 3: Use writelines()

lines = ["First line\n", "Second line\n", "Third line\n"]
f = open("output.txt", "w")
f.writelines(lines)
f.close()

The writelines() method writes all lines from a list at once.

writelines() सभी lines को एक साथ list से लिखता है।

Example 4: Append to Existing File

f = open("output.txt", "a")
f.write("New line added.\n")
f.close()

Using "a" mode, you can add content to the end of an existing file.

"a" mode से पहले से बनी file के अंत में नई line जोड़ सकते हैं।