Python - Write to a file

  Create a new file

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

x - (create)—Creates a file and returns an error if the file already exists.

a - (Append)—Creates the file only if it does not exist.

w - (Write): creates the file only if it does not exist.

Example:

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

Edit an existing file

To write to a file that already exists, you need to add an opening parameter to the open() function:

a - Append: Concatenate at the end of the file.

w - Write: Overwrite the existing content with the new one.

Example:

f=open("demo.txt", "a")
f.write("Content added!")
f.close()

#ouvrir and read the file after the concatenation
f = open("demo.txt", "r")
print(f.read())

In this example the contents and add to the end of the demo.txt file.