Skip to content

Exercise 11: Write file

Alternative course

Creating new files
To create new files, you can use this code:

#!/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.

#!/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()

Study drill

Try the exercises below

1. Create a file that writes a text file to your computer

Answers

Exercise 10: Read file
Exercise 13 : Nested loops
Published inUncategorized

Be First to Comment

    Leave a Reply