Python File Append

What is File Appending?

Appending a file means adding new data at the end of an existing file without deleting or overwriting the current content.

In Python, opening a file in append mode 'a' allows you to add new data at the file's end safely.

This is useful for logging, saving new entries, or adding incremental data without losing previous information.

फाइल में अपेंड करने का मतलब है मौजूदा फाइल के अंत में नया डेटा जोड़ना बिना पुराने डेटा को हटाए या बदलें।

Python में, फाइल को अपेंड मोड 'a' में खोलकर आप नई जानकारी फाइल के अंत में सुरक्षित रूप से जोड़ सकते हैं।

यह लॉगिंग, नए एंट्री जोड़ने, या डेटा को क्रमिक रूप से अपडेट करने के लिए उपयोगी होता है बिना पुराने डेटा खोए।

5 Examples of File Appending in Python

Example 1: Append a Single Line to a Text File

with open('log.txt', 'a') as file:
    file.write('New log entry\n')
Output:
Adds a new line 'New log entry' to the end of 'log.txt'.

This code opens 'log.txt' in append mode and writes a new line at the end.

यह कोड 'log.txt' को अपेंड मोड में खोलता है और अंत में एक नई लाइन जोड़ता है।

Example 2: Append Multiple Lines Using writelines()

lines = ['First line\n', 'Second line\n', 'Third line\n']
with open('log.txt', 'a') as file:
    file.writelines(lines)
Output:
Adds three lines at the end of 'log.txt'.

writelines() appends multiple lines from a list to the file.

writelines() एक लिस्ट से कई लाइनें फाइल के अंत में जोड़ता है।

Example 3: Append Text with Encoding Specified

with open('log.txt', 'a', encoding='utf-8') as file:
    file.write('अपेंडिंग UTF-8 में\n')
Output:
Appends a UTF-8 encoded Hindi text line safely.

Specifying encoding ensures correct handling of non-ASCII characters during append.

एनकोडिंग निर्दिष्ट करने से गैर-ASCII अक्षरों को सही तरीके से अपेंड किया जा सकता है।

Example 4: Appending Numbers Converted to String

with open('numbers.txt', 'a') as file:
    for i in range(1, 4):
        file.write(str(i) + '\n')
Output:
Appends numbers 1, 2, 3 each on a new line at the end of 'numbers.txt'.

Convert numbers to string before appending since file.write() accepts strings.

file.write() केवल स्ट्रिंग स्वीकार करता है, इसलिए नंबर को स्ट्रिंग में बदलकर अपेंड करें।

Example 5: Append User Input to a File

user_input = input('Enter a note to save: ')
with open('notes.txt', 'a') as file:
    file.write(user_input + '\n')
Output:
Appends user input text to 'notes.txt'.

User input is taken and appended to the file as a new line.

यूज़र इनपुट लेकर उसे फाइल में नई लाइन के रूप में जोड़ता है।

© 2025 Login Technologies. All rights reserved.

Learn to Code Anytime, Anywhere | Contact Us