8.3. File Write

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

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

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

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

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

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

8.3.7. Reading From One File and Writing to Another

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

8.3.8. Assignments

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

English:
    1. Use data from "Given" section (see below)
    2. Write `DATA` to file `FILE`
    3. Check in your operating system if data was written correctly
    4. Compare result with "Tests" section (see below)

Polish:
    1. Użyj danych z sekcji "Given" (patrz poniżej)
    2. Zapisz `DATA` do pliku `FILE`
    3. Sprawdź w systemie operacyjnym czy dane zapisały się poprawnie
    4. Porównaj wyniki z sekcją "Tests" (patrz poniżej)

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

Tests:
    >>> open(FILE).read()
    'hello world\\n'
    >>> from os import remove
    >>> remove(FILE)
"""


# Given
FILE = r'_temporary.txt'
DATA = 'hello world'


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

English:
    1. Use data from "Given" section (see below)
    2. Write `DATA` to file `FILE`
    3. Check in your operating system if data was written correctly
    4. Compare result with "Tests" section (see below)

Polish:
    1. Użyj danych z sekcji "Given" (patrz poniżej)
    2. Zapisz `DATA` do pliku `FILE`
    3. Sprawdź w systemie operacyjnym czy dane zapisały się poprawnie
    4. Porównaj wyniki z sekcją "Tests" (patrz poniżej)

Tests:
    >>> 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'
    >>> from os import remove
    >>> remove(FILE)
"""


# Given
FILE = r'_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 8.5. Solution
"""
* Assignment: File Write List
* Complexity: easy
* Lines of code: 3 lines
* Time: 3 min

English:
    1. Use data from "Given" section (see below)
    2. Write `DATA` to file `FILE`
    3. Check in your operating system if data was written correctly
    4. Compare result with "Tests" section (see below)

Polish:
    1. Użyj danych z sekcji "Given" (patrz poniżej)
    2. Zapisz `DATA` do pliku `FILE`
    3. Sprawdź w systemie operacyjnym czy dane zapisały się poprawnie
    4. Porównaj wyniki z sekcją "Tests" (patrz poniżej)

Hints:
    * `','.join(...)`
    * Add newline `\n` at the end of line and file

Tests:
    >>> open(FILE).read()
    'hello\\nworld\\n'
    >>> from os import remove
    >>> remove(FILE)
"""


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


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

English:
    1. Use data from "Given" section (see below)
    2. Write `DATA` to file `FILE`
    3. Check in your operating system if data was written correctly
    4. Compare result with "Tests" section (see below)

Polish:
    1. Użyj danych z sekcji "Given" (patrz poniżej)
    2. Zapisz `DATA` do pliku `FILE`
    3. Sprawdź w systemie operacyjnym czy dane zapisały się poprawnie
    4. Porównaj wyniki z sekcją "Tests" (patrz poniżej)

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

Tests:
    >>> open(FILE).read()
    '5.1,3.5,1.4,0.2,setosa\\n'
    >>> from os import remove
    >>> remove(FILE)
"""


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


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

English:
    1. Use data from "Given" section (see below)
    2. Write `DATA` to file `FILE`
    3. Check in your operating system if data was written correctly
    4. Compare result with "Tests" section (see below)

Polish:
    1. Użyj danych z sekcji "Given" (patrz poniżej)
    2. Zapisz `DATA` do pliku `FILE`
    3. Sprawdź w systemie operacyjnym czy dane zapisały się poprawnie
    4. Porównaj wyniki z sekcją "Tests" (patrz poniżej)

Hints:
    * `','.join(...)`
    * Add newline `\n` at the end of line and file

Tests:
    >>> 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'
    >>> from os import remove
    >>> remove(FILE)
"""


# Given
FILE = r'_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 8.8. Solution
"""
* Assignment: File Write CSV
* Complexity: medium
* Lines of code: 6 lines
* Time: 5 min

English:
    1. Use data from "Given" section (see below)
    2. Separate header from data
    3. Write data to file: `FILE`
    4. First line in file must be a header (first line of `DATA`)
    5. For each row, convert it's values to `str`
    6. Use coma (`,`) as a value separator
    7. Add line terminator (`\n`) to each row
    8. Save row values to file

Polish:
    1. Użyj danych z sekcji "Given" (patrz poniżej)
    2. Odseparuj nagłówek od danych
    3. Zapisz dane do pliku: `FILE`
    4. Pierwsza linia w pliku musi być nagłówkiem (pierwsza linia `DATA`)
    5. Dla każdego wiersza przekonwertuj jego wartości do `str`
    6. Użyj przecinka (`,`) jako separatora wartości
    7. Użyj `\n` jako koniec linii w każdym wierszu
    8. Zapisz do pliku wartości z wiersza

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

Tests:
    >>> 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>
    >>> from os import remove
    >>> remove(FILE)
"""


# Given
FILE = r'_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'),
]


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