File Methods
write()
Write a string or bytes to the file stream.
file.write(string)
file.write() writes the contents of string to the file stream at the current position.
Returns the number of characters (or bytes in binary mode) written.
Parameters
| Name | Description |
|---|---|
| string | The text or bytes string to write to the file. |
Returns
The integer number of characters or bytes written.
Try it
Run it and change it
import tempfile
with tempfile.NamedTemporaryFile(mode='w+', delete=True) as f:
chars_written = f.write('PyQuest')
print('Characters written:', chars_written)Worth knowing
- No automatic newline: Unlike
print(),file.write()does not append a newline character automatically; you must append\nexplicitly.