Python Tutorial

Python File Write and Create New File

How to Write a File in Python

To write to an existing file, use the open() method with the following parameter:

  • "a" - Append: This will append value to the end of the file

  • "w" - Write: This will erase any existing content and write new value

Example:

Open the file "wscfile2.txt" and append content to the file:

p = open("wscube2.txt", "a")

p.write("Now the file has more content!")

p.close()

p = open("wscube2.txt", "r")

print(p.read())

Output:

C:\Users\My Name>python demo_file_append.py
Hello! Welcome to wscube2.txt
This file is for testing purposes.
Good Luck! Now the file has more content!

How to Create a New File in Python?

Use the open() function with one of the following parameters to create a new file in Python:

  • "x" - Create: It will create a file. If the file already exists, it will return an error.

  • "a" - Append: It will create a file. In case the file doesn’t exist, it will create a new one.

  • "w" - Write: It will create a file if the file does not exist.

Example:

Create a file called "my_file.txt":

p = open("my_file.txt", "x")

Result: a new empty file is created!

Example:

Create a new file in case it doesn’t exist:

p = open("my_file.txt", "w")
Did you find this article helpful?