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.
Arguments
Parameters
| Name | Description |
|---|---|
| string | The text or bytes string to write to the file. |
Result
Returns
The integer number of characters or bytes written.
Run it
Try it
Run it and change it
import tempfile
with tempfile.NamedTemporaryFile(mode='w+', delete=True) as f:
chars_written = f.write('PyLabs')
print('Characters written:', chars_written) Output
Press Run to see what it prints.Worth knowing
- No automatic newline: Unlike
print(),file.write()does not append a newline character automatically; you must append\nexplicitly.