Python File Write: Writing and Appending to Files

Understand how to write to and append content in existing files using Python. This guide covers the basics of creating new files and modifying existing ones with the open() function. Learn practical techniques for efficient file management in your Python applications.



Python File Write

Writing to files is a common task in Python. Here, we will explore how to write to an existing file, append content, and create new files.

Write to an Existing File

To write to an existing file, you must add a parameter to the open() function:

  • "a" - Append - will append to the end of the file
  • "w" - Write - will overwrite any existing content

Append Content to a File

Open the file "demofile2.txt" and append content to it:

Example

f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()

# Open and read the file after appending:
f = open("demofile2.txt", "r")
print(f.read())

Overwrite Content in a File

Open the file "demofile3.txt" and overwrite the content:

Example

f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()

# Open and read the file after overwriting:
f = open("demofile3.txt", "r")
print(f.read())

Note: The "w" method will overwrite the entire file.

Create a New File

To create a new file in Python, use the open() method with one of the following parameters:

  • "x" - Create - will create a file, returns an error if the file exists
  • "a" - Append - will create a file if the specified file does not exist
  • "w" - Write - will create a file if the specified file does not exist

Create a File

Create a file called "myfile.txt":

Example

f = open("myfile.txt", "x")

Result: A new empty file is created!

Create a New File if It Does Not Exist

Create a new file if it does not exist:

Example

f = open("myfile.txt", "w")