13.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()

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

13.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()

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

13.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)

13.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]

13.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)

13.6.7. References

13.6.8. Assignments

Code 13.1. Solution
"""
* Assignment: File Write Str
* Type: class assignment
* 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 13.2. Solution
"""
* Assignment: File Write Multiline
* Type: class assignment
* 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 13.3. Solution
"""
* Assignment: File Write List
* Type: class assignment
* 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 13.4. Solution
"""
* Assignment: File Write Non-Str
* Type: class assignment
* 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 13.5. Solution
"""
* Assignment: File Write Iris
* Type: class assignment
* 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 13.6. Solution
"""
* Assignment: File Write CSV
* Type: class assignment
* 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'),
]