Last modified: Sep 26, 2023 By Alexander Williams
Python Open File, Append, Create if Not Exist [Methods + Examples]
Example 1: Append Data to an Existing File
# Open a file in append mode
with open("my_file.txt", "a") as file:
# Write data to the file
file.write("This is new data.\n")
Output:
This is new data.
Example 2: Create a New File If It Doesn't Exist and Append Data
# Open a file in append mode, create it if it doesn't exist
with open("new_file.txt", "a+") as file:
# Write data to the file
file.write("This is new data in a new file.\n")
# Move the file cursor to the beginning
file.seek(0)
# Read and print the file content
file_content = file.read()
print("File Content:")
print(file_content)
Output:
File Content:
This is new data in a new file.
Example 3: Append Data to an Existing CSV File
import csv
# Data to append
new_data = ["John", "Doe", "john@example.com"]
# Open a CSV file in append mode
with open("data.csv", "a", newline="") as file:
csv_writer = csv.writer(file)
# Append the data as a new row
csv_writer.writerow(new_data)
Output:
John,Doe,john@example.com
Example 4: Create a New CSV File If It Doesn't Exist and Append Data
import csv
# Data to append
new_data = ["Alice", "Smith", "alice@example.com"]
# Open a CSV file in append mode, create it if it doesn't exist
with open("new_data.csv", "a+", newline="") as file:
csv_writer = csv.writer(file)
# Append the data as a new row
csv_writer.writerow(new_data)
# Move the file cursor to the beginning
file.seek(0)
# Read and print the file content
file_content = file.read()
print("File Content:")
print(file_content)
Output:
File Content:
Alice,Smith,alice@example.com