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. Use newline as line terminator
    3. Run doctests - all must succeed

Polish:
    1. Zapisz `DATA` do pliku `FILE`
    2. Użyj newline jako terminator linii
    3. 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'

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

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. Use newline as line terminator
    3. Run doctests - all must succeed

Polish:
    1. Zapisz `DATA` do pliku `FILE`
    2. Użyj newline jako terminator linii
    3. 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)
    Fist line
    Second line
    Third line
    <BLANKLINE>
"""

FILE = '_temporary.txt'

DATA = """Fist line
Second line
Third line
"""

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

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. Use newline as line terminator
    3. Use comma as field separator
    4. Run doctests - all must succeed

Polish:
    1. Zapisz `DATA` do pliku `FILE`
    2. Użyj newline jako terminator linii
    3. Użyj przecinek jako separatora pól
    4. 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
    'sepal_length,sepal_width,petal_length,petal_width,species\\n'
"""

FILE = '_temporary.txt'
DATA = ('sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'species')

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


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. Use newline as line terminator
    3. Use comma as field separator
    4. Run doctests - all must succeed

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

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

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

Code 13.5. Solution
"""
* Assignment: File Write CSV
* Type: class assignment
* Complexity: medium
* Lines of code: 6 lines
* Time: 5 min

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

Polish:
    1. Zapisz `DATA` do pliku `FILE`
    2. Użyj newline jako terminator linii
    3. Użyj przecinek jako separatora pól
    4. 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'),
]

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

Code 13.6. Solution
"""
* Assignment: File Write Iris
* Type: class assignment
* Complexity: easy
* Lines of code: 7 lines
* Time: 8 min

English:
    1. Flatten `DATA` to list of strings
    2. Write `DATA` to file `FILE`
    3. Use newline as line terminator
    4. Use tab as field separator
    5. Run doctests - all must succeed

Polish:
    1. Spłaszcz `DATA` do listy stringów
    2. Zapisz `DATA` do pliku `FILE`
    3. Użyj newline jako terminator linii
    4. Użyj tab jako separatora pól
    5. Uruchom doctesty - wszystkie muszą się powieść

Hints:
    * `\t` - tab
    * `str.join()`
    * `list.append()`
    * 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)  # doctest: +NORMALIZE_WHITESPACE
    127.0.0.1 localhost
    10.13.37.1 nasa.gov esa.int
    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'],
    '255.255.255.255': ['broadcasthost'],
    '::1': ['localhost']
}

# Flatten `DATA` to list of strings
# Write `DATA` to file `FILE`
# Use newline as line terminator
# Use tab as field separator
...