13.4. File Write

  • Creates file if not exists

  • Truncate the file before writing

  • Works with both relative and absolute path

  • Fails when directory with file cannot be accessed

  • mode parameter to open() function is required

  • Line must end with a newline \n character

  • File must end with a newline \n character

13.4.1. Line

  • Line must end with a newline \n character

  • File must end with a newline \n character

  • POSIX Definition: A sequence of zero or more non-<newline> characters plus a terminating <newline> character.

>>> line = 'This is a line\n'

Line Definition by POSIX [1]:

A sequence of zero or more non-<newline> characters plus a terminating <newline> character.

When writing output to the stream, if newline is None, any '\n' characters written are translated to the system default line separator, os.linesep. If newline is '' or '\n', no translation takes place. If newline is any of the other legal values, any '\n' characters written are translated to the given string. [2]

13.4.2. Open for Writing

  • Python will create file if it does not exist

  • By default, file is opened in text mode

  • Always remember to close file

>>> file = open('/tmp/myfile.txt', mode='w')   # write in text mode
>>> file = open('/tmp/myfile.txt', mode='wt')  # write in text mode
>>> file = open('/tmp/myfile.txt', mode='wb')  # write in binary mode

13.4.3. Write One Line

>>> line = 'This is a line\n'
>>>
>>> file = open('/tmp/myfile.txt', mode='w')
>>> file.write(line)
15
>>> file.close()

13.4.4. Write Many Lines

  • Write a list of lines to the file.

  • Method .writelines() does not add a line separator (\n)!!

  • Each line must add a separator at the end

  • Remember to add a newline character at the end of the line

>>> lines = [
...     'This is a first line\n',
...     'This is a second line\n',
...     'This is a third line\n',
... ]
>>>
>>> file = open('/tmp/myfile.txt', mode='w')
>>> file.writelines(lines)
>>> file.close()

13.4.5. Write Non-Str Data

  • Join works only for strings

  • Conversion to str must be performed before adding a separator and writing to file

  • Remember to add a newline character at the end of the line

>>> data = ['Mark', 'Watney', 40]
>>> line = ''.join(str(x) for x in data) + '\n'
>>>
>>> file = open('/tmp/myfile.txt', mode='w')
>>> file.write(line)
13
>>> file.close()

13.4.6. Context Manager

  • Context managers use with ... as ...: syntax

  • Context manager closes the file automatically upon block exit (dedent)

  • Remember to add a newline character at the end of the line

with statement is a context manager. It is used to wrap the execution of a block of code. This way, you can ensure that resources are properly managed and released. [2]

>>> line = 'This is a line\n'
>>>
>>> with open('/tmp/myfile.txt', mode='w') as file:
...     file.write(line)
15

Does exactly the same as:

>>> file = open('/tmp/myfile.txt', mode='w')
>>> file.write(line)
15
>>> file.close()

Also, it closes the file automatically upon block exit (dedent).

13.4.7. Recap

  • Creates file if not exists

  • Truncate the file before writing

  • Works with both relative and absolute path

  • Fails when directory with file cannot be accessed

  • mode parameter to open() function is required

  • Line must end with a newline \n character

  • File must end with a newline \n character

13.4.8. References

13.4.9. Assignments

# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`

# %% About
# - Name: File Write Write
# - Difficulty: easy
# - Lines: 2
# - Minutes: 2

# %% English
# 1. Write `DATA` to file `FILE`
# 2. Run doctests - all must succeed

# %% Polish
# 1. Zapisz `DATA` do pliku `FILE`
# 2. Uruchom doctesty - wszystkie muszą się powieść

# %% Hints
# - Add newline `\n` at the end of each line and a file
# - `with`
# - `open`

# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> from os import remove
>>> result = open(FILE).read()
>>> remove(FILE)

>>> assert result is not Ellipsis, \
'Assign your result to variable `result`'
>>> assert type(result) is str, \
'Variable `result` has invalid type, should be str'
>>> assert result.endswith('\\n'), \
'File must ends with newline `\\\\n` character'

>>> print(result)
Mark Watney
<BLANKLINE>
"""

FILE = '_temporary.txt'
DATA = 'Mark Watney\n'

# Write `DATA` to file `FILE`
...


# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`

# %% About
# - Name: File Write Writelines
# - Difficulty: easy
# - Lines: 2
# - Minutes: 2

# %% English
# 1. Write `DATA` to file `FILE`
# 2. Run doctests - all must succeed

# %% Polish
# 1. Zapisz `DATA` do pliku `FILE`
# 2. Uruchom doctesty - wszystkie muszą się powieść

# %% Hints
# - Add newline `\n` at the end of each line and a file
# - `str.join()`
# - `with`
# - `open`

# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> from os import remove
>>> result = open(FILE).read()
>>> remove(FILE)

>>> assert result is not Ellipsis, \
'Assign your result to variable `result`'
>>> assert type(result) is str, \
'Variable `result` has invalid type, should be str'
>>> assert result.endswith('\\n'), \
'File must ends with newline `\\\\n` character'

>>> print(result)
Mark Watney
Melissa Lewis
Rick Martinez
<BLANKLINE>
"""

FILE = '_temporary.txt'

DATA = [
    'Mark Watney\n',
    'Melissa Lewis\n',
    'Rick Martinez\n',
]

# Write `DATA` to file `FILE`
...


# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`

# %% About
# - Name: File Write Tuple of Str
# - Difficulty: easy
# - Lines: 3
# - Minutes: 3

# %% English
# 1. Write `DATA` to file `FILE`
# 2. Use comma as field separator
# 3. Use newline as line terminator
# 4. Run doctests - all must succeed

# %% Polish
# 1. Zapisz `DATA` do pliku `FILE`
# 2. Użyj przecinek jako separatora pól
# 3. Użyj newline jako terminator linii
# 4. Uruchom doctesty - wszystkie muszą się powieść

# %% Hints
# - Add newline `\n` at the end of each line and a file
# - `str.join()`
# - `with`
# - `open`

# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> from os import remove
>>> result = open(FILE).read()
>>> remove(FILE)

>>> assert result is not Ellipsis, \
'Assign your result to variable `result`'
>>> assert type(result) is str, \
'Variable `result` has invalid type, should be str'
>>> assert result.endswith('\\n'), \
'File must ends with newline `\\\\n` character'

>>> print(result)
firstname,lastname,age
<BLANKLINE>
"""

FILE = '_temporary.txt'
DATA = ('firstname', 'lastname', 'age')

# Write `DATA` to file `FILE`
# Use comma as field separator
# Use newline as line terminator
...


# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`

# %% About
# - Name: File Write Tuple of Non-Str
# - Difficulty: easy
# - Lines: 3
# - Minutes: 3

# %% English
# 1. Write `DATA` to file `FILE`
# 2. Use comma as field separator
# 3. Use newline as line terminator
# 4. Run doctests - all must succeed

# %% Polish
# 1. Zapisz `DATA` do pliku `FILE`
# 2. Użyj przecinek jako separatora pól
# 3. Użyj newline jako terminator linii
# 4. Uruchom doctesty - wszystkie muszą się powieść

# %% Hints
# - Add newline `\n` at the end of each line and a file
# - `[str(x) for x in ...]`
# - `str.join()`
# - `with`
# - `open`

# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> from os import remove
>>> result = open(FILE).read()
>>> remove(FILE)

>>> assert result is not Ellipsis, \
'Assign your result to variable `result`'
>>> assert type(result) is str, \
'Variable `result` has invalid type, should be str'
>>> assert result.endswith('\\n'), \
'File must ends with newline `\\\\n` character'

>>> print(result)
Mark,Watney,41
<BLANKLINE>
"""

FILE = '_temporary.txt'
DATA = ('Mark', 'Watney', 41)

# Write `DATA` to file `FILE`
# Use comma as field separator
# Use newline as line terminator
...


# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`

# %% About
# - Name: File Write CSV
# - Difficulty: medium
# - Lines: 4
# - Minutes: 5

# %% English
# 1. Write `DATA` to file `FILE`
# 2. Use comma as field separator
# 3. Use newline as line terminator
# 4. Run doctests - all must succeed

# %% Polish
# 1. Zapisz `DATA` do pliku `FILE`
# 2. Użyj przecinek jako separatora pól
# 3. Użyj newline jako terminator linii
# 4. Uruchom doctesty - wszystkie muszą się powieść

# %% Hints
# - Add newline `\n` at the end of each line and a file
# - `str.join()`
# - `[str(x) for x in ...]`

# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> from os import remove
>>> result = open(FILE).read()
>>> remove(FILE)

>>> assert result is not Ellipsis, \
'Assign your result to variable `result`'
>>> assert type(result) is str, \
'Variable `result` has invalid type, should be str'
>>> assert result.endswith('\\n'), \
'File must ends with newline `\\\\n` character'

>>> print(result)
firstname,lastname,age
Mark,Watney,41
Melissa,Lewis,40
Rick,Martinez,39
Alex,Vogel,40
Chris,Beck,36
Beth,Johanssen,29
<BLANKLINE>
"""

FILE = '_temporary.csv'

DATA = [
    ('firstname', 'lastname', 'age'),
    ('Mark', 'Watney', 41),
    ('Melissa', 'Lewis', 40),
    ('Rick', 'Martinez', 39),
    ('Alex', 'Vogel', 40),
    ('Chris', 'Beck', 36),
    ('Beth', 'Johanssen', 29),
]

# Write `DATA` to file `FILE`
# Use comma as field separator
# Use newline as line terminator
...