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

Appending Data to Files in Python

To append content to an existing file in Python, use the "a" mode in the open() function.

Python में किसी file में नया data जोड़ने के लिए "a" mode का इस्तेमाल होता है।

Example 1: Append Text to File

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

This will add a new line to the end of log.txt without erasing existing content.

यह existing file में नई लाइन जोड़ देगा बिना पहले का data हटाए।

Example 2: Append Multiple Lines

f = open("log.txt", "a")
f.write("User1 logged in\n")
f.write("User2 logged out\n")
f.close()

Appends two lines one after another.

यह दो लाइन को एक के बाद एक जोड़ता है।

Example 3: Using writelines() with Append

lines = ["Error: File not found\n", "Error: Timeout\n"]
f = open("log.txt", "a")
f.writelines(lines)
f.close()

You can use writelines() to append multiple lines from a list.

list से कई lines append करने के लिए writelines() का use किया गया है।

Note:

  • If the file doesn't exist, it will be created.
  • अगर file मौजूद नहीं है, तो यह बन जाएगी।
  • Use "a" mode only when you don’t want to erase old content.
  • "a" mode का उपयोग तभी करें जब आप पुराने data को बचाना चाहते हैं।