Write data to TXT / flat file using Python

Here’s an example code in Python to write data to a txt or flat file

# Define the data to be written
data = "This is a sample data that will be written to a txt file."

# Define the file path and name for the txt file
file_path = 'data.txt'

# Open the txt file in write mode
with open(file_path, mode='w') as txt_file:

    # Write the data to the txt file
    txt_file.write(data)

print(f'Data has been written to {file_path} successfully.')

This code defines a string data to be written to a txt file, sets the file path and name for the txt file, opens the txt file in write mode, and writes the data to the txt file using the write() method. Finally, it prints a message to indicate that the data has been written successfully.

Pamai Tech
Turning ideas into Reality

Products

Office Add-in

Enterprise Solutions

Cloud Consulting

UI UX Design

Data Transformation

Services

FAQ's

Privacy Policy

Terms & Condition

Team

Contact Us

Company

About Us

Services

Features

Our Pricing

Latest News

© 2025 Pamai Tech