File Handling

Write


Text file content

We are so happy that you are here. This just a test file. To show how file handling in python works.

Append to an existing file

To write in a file uses append ("a") mode while opening.

Example

f = open("file.txt", "a")
f.write("Append file!")
f.close()
f = open("file.txt", "r")
print(f.read())

Output

We are so happy that you are here. This just a test file. To show how file handling in python works. Append file!

Write to an existing file

To write in a file uses write ("w") mode while opening.

Example

f = open("file.txt", "w")
f.write("New content in file!")
f.close()
f = open("file.txt", "r")
print(f.read())

Output

New content in file!

Create

Both "a" and "w" will create a file if file does not exist when the prompt is given to open the file.

While "x" will create a file and open it for writing.