Python File Write

Write to an existing file

To write to an existing file, it is necessary to open() Function adds parameters:

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

Example

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

f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
# After appending, open and read the file:
f = open("demofile2.txt", "r")
print(f.read())

Run the example

Example

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

f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()
# After writing, open and read the file:
f = open("demofile3.txt", "r")
print(f.read())

Run the example

Note:The "w" method will overwrite all content.

Create New File

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

  • "x" - Create - A file will be created, and an error will be returned if the file already exists
  • "a" - Append - If the specified file does not exist, a file will be created
  • "w" - Write - If the specified file does not exist, a file will be created

Example

Create a file named "myfile.txt":

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

Result: A new empty file has been created!

Example

If it does not exist, create a new file:

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