10.6. 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

>>> file = open(r'/tmp/myfile.txt', mode='w')
>>> file.write('hello')
5
>>> file.close()

10.6.1. Line

  • 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 Definition by POSIX 1:

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

Line definition by ANSI C89 and ISO C99 standards 2, 3, 4:

A source file that is not empty shall end in a new-line character, which shall not be immediately preceded by a backslash character.

10.6.2. Write to File

  • Always remember to close file

>>> FILE = r'/tmp/myfile.txt'
>>> DATA = 'We choose to go to the Moon...'
>>>
>>> file = open(FILE, mode='w')
>>> file.write(DATA)
30
>>> file.close()

10.6.3. Write One Line

>>> FILE = r'/tmp/myfile.txt'
>>> DATA = 'We choose to go to the Moon...'
>>>
>>> with open(FILE, mode='w') as file:
...     file.write(DATA)
30

10.6.4. Write Multiple Lines

  • Write a list of lines to the file.

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

  • Each line must add a separator at the end.

>>> FILE = r'/tmp/myfile.txt'
>>> DATA = ['We choose to go to the Moon.',
...         'We choose to go to the Moon in this decade and do the other things.',
...         'Not because they are easy, but because they are hard.']
>>>
>>> result = '\n'.join(DATA)
>>>
>>> with open(FILE, mode='w') as file:
...     file.write(result)
150
>>> FILE = r'/tmp/myfile.txt'
>>> DATA = ['We choose to go to the Moon.',
...         'We choose to go to the Moon in this decade and do the other things.',
...         'Not because they are easy, but because they are hard.']
>>>
>>> result = [line+'\n' for line in DATA]
>>>
>>> with open(FILE, mode='w') as file:
...     file.writelines(result)

10.6.5. Write Non-Str Data

  • Join works only for strings

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

>>> FILE = r'/tmp/myfile.txt'
>>> DATA = [1, 2, 3]
>>>
>>> result = ','.join(str(x) for x in DATA) + '\n'
>>>
>>> with open(FILE, mode='w') as file:
...     file.write(result)
6

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. 5

10.6.6. Reading From One File and Writing to Another

>>> FILE_READ = r'/tmp/my-infile.txt'
>>> FILE_WRITE = r'/tmp/my-outfile.txt'
>>>
>>> 
... with open(FILE_READ) as infile, \
...     open(FILE_WRITE, mode='w') as outfile:
...
...     for line in infile:
...         outfile.write(line)

10.6.7. References

1

Section 3.206 IEEE Std 1003.1-2017 (Revision of IEEE Std 1003.1-2008). Open Group Base Specifications Issue 7. Year: 2018. Retrieved: 2020-12-17. URL: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_206

2

Section 2.1.1.2 of the ANSI C 1989 standard

3

Section 5.1.1.2 of the ISO C 1999 standard

4

https://gcc.gnu.org/legacy-ml/gcc/2003-11/msg01568.html

5

https://docs.python.org/3/library/io.html#io.TextIOWrapper

10.6.8. Assignments

Code 10.9. Solution
"""
* Assignment: File Write Str
* Required: yes
* Complexity: easy
* Lines of code: 3 lines
* Time: 3 min

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 line and file
    * `with`
    * `open`

Tests:
    >>> import sys; sys.tracebacklimit = 0
    >>> from os import remove
    >>> result = open(FILE).read()
    >>> remove(FILE)

    >>> result
    'hello world\\n'
"""

FILE = '_temporary.txt'
DATA = 'hello world'

Code 10.10. Solution
"""
* Assignment: File Write Multiline
* Required: yes
* Complexity: easy
* Lines of code: 3 lines
* Time: 3 min

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:
    * There is already a newline `\n` at the end of file
    * `with`
    * `open`

Tests:
    >>> import sys; sys.tracebacklimit = 0
    >>> from os import remove
    >>> result = open(FILE).read()
    >>> remove(FILE)

    >>> print(result)
    127.0.0.1       localhost
    10.13.37.1      nasa.gov esa.int polsa.gov.pl
    255.255.255.255 broadcasthost
    ::1             localhost
    <BLANKLINE>
"""

FILE = '_temporary.txt'
DATA = """127.0.0.1       localhost
10.13.37.1      nasa.gov esa.int polsa.gov.pl
255.255.255.255 broadcasthost
::1             localhost"""


Code 10.11. Solution
"""
* Assignment: File Write List
* Required: yes
* Complexity: easy
* Lines of code: 3 lines
* Time: 3 min

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 line and file
    * `str.join()`
    * `with`
    * `open`

Tests:
    >>> import sys; sys.tracebacklimit = 0
    >>> from os import remove
    >>> result = open(FILE).read()
    >>> remove(FILE)

    >>> result
    'hello,world\\n'
"""

FILE = '_temporary.txt'
DATA = ['hello', 'world']

Code 10.12. Solution
"""
* Assignment: File Write Non-Str
* Required: yes
* Complexity: easy
* Lines of code: 3 lines
* Time: 3 min

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 line and file
    * `[str(x) for x in data]`
    * `str.join()`
    * `with`
    * `open`

Tests:
    >>> import sys; sys.tracebacklimit = 0
    >>> from os import remove
    >>> result = open(FILE).read()
    >>> remove(FILE)

    >>> result
    '5.1,3.5,1.4,0.2,setosa\\n'
"""

FILE = '_temporary.txt'
DATA = (5.1, 3.5, 1.4, 0.2, 'setosa')

Code 10.13. Solution
"""
* Assignment: File Write Iris
* Required: yes
* Complexity: easy
* Lines of code: 3 lines
* Time: 5 min

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:
    * `','.join(...)`
    * Add newline `\n` at the end of line and file

Tests:
    >>> import sys; sys.tracebacklimit = 0
    >>> from os import remove
    >>> result = open(FILE).read()
    >>> remove(FILE)

    >>> print(result)
    5.8,2.7,5.1,1.9
    5.1,3.5,1.4,0.2
    5.7,2.8,4.1,1.3
    <BLANKLINE>
"""

FILE = '_temporary.txt'
DATA = [
    ('5.8', '2.7', '5.1', '1.9'),
    ('5.1', '3.5', '1.4', '0.2'),
    ('5.7', '2.8', '4.1', '1.3'),
]

Code 10.14. Solution
"""
* Assignment: File Write CSV
* Required: yes
* Complexity: medium
* Lines of code: 6 lines
* Time: 5 min

English:
    1. Separate header from data
    2. Write data to file `FILE`:
        a. First line in file must be a header (first line of `DATA`)
        b. For each row, convert it's values to `str`
        c. Use coma (`,`) as a value separator
        d. Add line terminator (`\n`) to each row
        e. Save row values to file
    8. Run doctests - all must succeed

Polish:
    1. Odseparuj nagłówek od danych
    2. Zapisz dane do pliku `FILE`:
        a. Pierwsza linia w pliku musi być nagłówkiem (pierwsza linia `DATA`)
        b. Dla każdego wiersza przekonwertuj jego wartości do `str`
        c. Użyj przecinka (`,`) jako separatora wartości
        d. Użyj `\n` jako koniec linii w każdym wierszu
        e. Zapisz do pliku wartości z wiersza
    8. Uruchom doctesty - wszystkie muszą się powieść

Hints:
    * `','.join(...)`
    * `[str(x) for x in ...]`
    * Add newline `\n` at the end of line and file

Tests:
    >>> import sys; sys.tracebacklimit = 0
    >>> from os import remove
    >>> result = open(FILE).read()
    >>> remove(FILE)

    >>> print(result)
    Sepal length,Sepal width,Petal length,Petal width,Species
    5.8,2.7,5.1,1.9,virginica
    5.1,3.5,1.4,0.2,setosa
    5.7,2.8,4.1,1.3,versicolor
    6.3,2.9,5.6,1.8,virginica
    6.4,3.2,4.5,1.5,versicolor
    4.7,3.2,1.3,0.2,setosa
    <BLANKLINE>
"""

FILE = '_temporary.csv'
DATA = [
    ('Sepal length', 'Sepal width', 'Petal length', 'Petal width', 'Species'),
    (5.8, 2.7, 5.1, 1.9, 'virginica'),
    (5.1, 3.5, 1.4, 0.2, 'setosa'),
    (5.7, 2.8, 4.1, 1.3, 'versicolor'),
    (6.3, 2.9, 5.6, 1.8, 'virginica'),
    (6.4, 3.2, 4.5, 1.5, 'versicolor'),
    (4.7, 3.2, 1.3, 0.2, 'setosa'),
]