14.3. File Write

14.3.1. Rationale

  • 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()

14.3.2. Line

  • File must end with a newline \n 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 language 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.

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

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

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

14.3.6. 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. Source: https://docs.python.org/3/library/io.html#io.TextIOWrapper

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

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

14.3.9. Assignments

Code 14.3. 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. Check in your operating system if data was written correctly
    3. Run doctests - all must succeed

Polish:
    1. Zapisz `DATA` do pliku `FILE`
    2. Sprawdź w systemie operacyjnym czy dane zapisały się poprawnie
    3. Uruchom doctesty - wszystkie muszą się powieść

Hints:
    * Add newline `\n` at the end of line and file

Tests:
    >>> import sys; sys.tracebacklimit = 0
    >>> from os import remove

    >>> open(FILE).read()
    'hello world\\n'

    >>> remove(FILE)
"""

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

Code 14.4. 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. Check in your operating system if data was written correctly
    3. Run doctests - all must succeed

Polish:
    1. Zapisz `DATA` do pliku `FILE`
    2. Sprawdź w systemie operacyjnym czy dane zapisały się poprawnie
    3. Uruchom doctesty - wszystkie muszą się powieść

Tests:
    >>> import sys; sys.tracebacklimit = 0
    >>> from os import remove

    >>> open(FILE).read()
    '127.0.0.1       localhost\\n10.13.37.1      nasa.gov esa.int roscosmos.ru\\n255.255.255.255 broadcasthost\\n::1             localhost\\n'

    >>> remove(FILE)
"""

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

Code 14.5. 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. Check in your operating system if data was written correctly
    3. Run doctests - all must succeed

Polish:
    1. Zapisz `DATA` do pliku `FILE`
    2. Sprawdź w systemie operacyjnym czy dane zapisały się poprawnie
    3. 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

    >>> open(FILE).read()
    'hello\\nworld\\n'

    >>> remove(FILE)
"""

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

Code 14.6. 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. Check in your operating system if data was written correctly
    3. Run doctests - all must succeed

Polish:
    1. Zapisz `DATA` do pliku `FILE`
    2. Sprawdź w systemie operacyjnym czy dane zapisały się poprawnie
    3. Uruchom doctesty - wszystkie muszą się powieść

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

Tests:
    >>> import sys; sys.tracebacklimit = 0
    >>> from os import remove

    >>> open(FILE).read()
    '5.1,3.5,1.4,0.2,setosa\\n'

    >>> remove(FILE)
"""

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

Code 14.7. 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. Check in your operating system if data was written correctly
    3. Run doctests - all must succeed

Polish:
    1. Zapisz `DATA` do pliku `FILE`
    2. Sprawdź w systemie operacyjnym czy dane zapisały się poprawnie
    3. 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

    >>> open(FILE).read()
    '5.8,2.7,5.1,1.9\\n5.1,3.5,1.4,0.2\\n5.7,2.8,4.1,1.3\\n'

    >>> remove(FILE)
"""

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 14.8. 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`
    3. First line in file must be a header (first line of `DATA`)
    4. For each row, convert it's values to `str`
    5. Use coma (`,`) as a value separator
    6. Add line terminator (`\n`) to each row
    7. Save row values to file
    8. Run doctests - all must succeed

Polish:
    1. Odseparuj nagłówek od danych
    2. Zapisz dane do pliku: `FILE`
    3. Pierwsza linia w pliku musi być nagłówkiem (pierwsza linia `DATA`)
    4. Dla każdego wiersza przekonwertuj jego wartości do `str`
    5. Użyj przecinka (`,`) jako separatora wartości
    6. Użyj `\n` jako koniec linii w każdym wierszu
    7. 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()
    >>> 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>

    >>> remove(FILE)
"""

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'),
]