Python File write() Method
Example
Open the file with "a" for appending and then add some text to the file:
f = open("demofile2.txt", "a") f.write("See you soon!") f.close() #open and read the file after the appending: f = open("demofile2.txt", "r") print(f.read())
Definition and Usage
The write() method writes the specified text to the file.
The position where the specified text will be inserted depends on the file mode and stream position.
"a": Text will be inserted at the current file stream position, by default inserting at the end of the file.
"w": Clear the file before inserting text at the current file stream position (default is 0).
Syntax
file.write(byte)
Parameter Value
Parameter | Description |
---|---|
byte | The text or byte object to be inserted. |
More Examples
Example
The same as the previous example, but insert a newline before the inserted text:
f = open("demofile2.txt", "a") f.write("\nSee you soon!") f.close() #open and read the file after the appending: f = open("demofile2.txt", "r") print(f.read())