Write file functionality is part of the standard module, you don't need to include any modules.

Writing files and appending to a file are different in the Python language.
You can open a file for writing using the line

1
f = open("test.txt","w")

to append to a file use:
1
f = open("test.txt","a")

If you specify the wrong parameter, your file could be emptied!

Related course: Complete Python Programming Course & Exercises

Examples

Creating new file

To create new files, you can use this code:

1
2
3
4
5
6
7
8
9
10
11
#!/usr/bin/env python

# create and open file
f = open("test.txt","w")

# write data to file
f.write("Hello World, \n")
f.write("This data will be written to the file.")

# close file
f.close()

The '\n' character adds a new line. If the file already exists, it is replaced. If you use the 'w' parameter, the existing contents of the file will be deleted.

Appending to files

To add text to the end of a file, use the 'a' parameter.

1
2
3
4
5
6
7
8
9
10
11
#!/usr/bin/env python

# create and open file
f = open("test.txt","a")

# write data to file
f.write("Don't delete existing data \n")
f.write("Add this to the existing file.")

# close file
f.close()

If you are a beginner, then I highly recommend this YouTube Python Playlist.

Exercise

  1. Write the text 'Take it easy' to a file
  2. Write the line open('text.txt') to a file