User Guide
Table Of Contents
152
If you specify more characters to read then the file has left,
Python reads as many characters as it can. When Python reaches
the end of the file, the string returned by a call to read() will have
a length of zero.
Writing Text to a File
To create a new text file and write a test message to it, open the
file using mode “w”. Then use the method write(). For example:
test = open("/home/pi/Desktop/Test.txt", "w")
test.write("Hello from Python!")
test.close()
If you run this example twice, you will see that the text file on
your desktop still only contains one sentence.
Appending Text to a File
To add content to the end of a file, use one of the “append”
modes when opening the file. For example:
test = open("/home/pi/Desktop/Test.txt", "a")
test.write("Another hello from Python!")
test.close()
If you open the file Test.txt now, you should see that the string
has been added to the end of the file.
Renaming and Deleting Files
To rename a file, import os and then use the rename() function:
import os
os.rename("/home/pi/Desktop/Test.txt", "/home/pi/Desktop/
Test2.txt")
To delete a file, use the remove() function:
import os
os.remove("/home/pi/Desktop/Test2.txt")