7.3. File Write

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

7.3.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)
file.close

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

7.3.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.']

data = '\n'.join(DATA)


with open(FILE, mode='w') as file:
    file.writelines(data)

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

data = '\n'.join(str(x) for x in DATA)


with open(FILE, mode='w') as file:
    file.writelines(data)

Note

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

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

7.3.7. Assignments

7.3.7.1. Save to CSV file

  • Complexity level: easy

  • Lines of code to write: 5 lines

  • Estimated time of completion: 15 min

  • Solution: solution/file_write.py

English
  1. Use data from "Input" section (see below)

  2. Separate header from data

  3. Write data to file: iris.csv

  4. First line in file must be a header

  5. Use coma (,) as a value separator

  6. Use utf-8 encoding and \n for line terminator

Polish
  1. Użyj danych z sekcji "Input" (patrz poniżej)

  2. Odseparuj nagłówek do danych

  3. Zapisz dane do pliku: iris.csv

  4. Pierwsza linia w pliku musi być nagłówkiem

  5. Użyj przecinka (,) jako separatora wartości

  6. Użyj kodowania utf-8 i \n jako koniec linii

Input
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'),
    (7.0, 3.2, 4.7, 1.4, 'versicolor'),
    (7.6, 3.0, 6.6, 2.1, 'virginica'),
    (4.9, 3.0, 1.4, 0.2, 'setosa'),
    (4.9, 2.5, 4.5, 1.7, 'virginica'),
    (7.1, 3.0, 5.9, 2.1, 'virginica'),
    (4.6, 3.4, 1.4, 0.3, 'setosa'),
    (5.4, 3.9, 1.7, 0.4, 'setosa'),
    (5.7, 2.8, 4.5, 1.3, 'versicolor'),
    (5.0, 3.6, 1.4, 0.3, 'setosa'),
    (5.5, 2.3, 4.0, 1.3, 'versicolor'),
    (6.5, 3.0, 5.8, 2.2, 'virginica'),
    (6.5, 2.8, 4.6, 1.5, 'versicolor'),
    (6.3, 3.3, 6.0, 2.5, 'virginica'),
    (6.9, 3.1, 4.9, 1.5, 'versicolor'),
    (4.6, 3.1, 1.5, 0.2, 'setosa'),
]