Перейти к содержанию

Работа с текстовыми файлами

Работа с файлами в текстовом режиме имеет некоторые приятные особенности в Python. Прежде всего файл — это поток или последовательность строк и было бы естественно работать с файлом как со списком строк. Поэтому Python позволяет использовать файл как источник данных, которые можно обрабатывать в цикле читая файл построчно, это эквивалентно скрытому вызову метода readlines(). Поскольку каждая строка возвращается как есть, то она будет содержать знаки новой строки в конце каждой строки. Функция print автоматически добавляет знак перевода строки, чтобы этого не было можно либо обрезать последний знак в строке, либо указать print не добавлять \n после каждого вывода print(line, end='').

Файл reader.py:

paper = open("turing_paper_1936.txt", "rt")

for line in paper:
    print(line[:-1])

paper.close()

Что выведет на экран содержимое файла turing_paper_1936.txt:

```txt ON COMPUTABLE NUMBERS, WITH AN APPLICATION TO THE ENTSCHEIDUNGSPROBLEM

                        By A. M. TURING.

        [Received 28 May, 1936.—Read 12 November, 1936.]

The "computable" numbers may be described briefly as the real numbers whose expressions as a decimal are calculable by finite means. Although the subject of this paper is ostensibly the computable numbers. it is almost equally easy to define and investigate computable functions of an integral variable or a real or computable variable, computable predicates, and so forth. The fundamental problems involved are, however, the same in each case, and I have chosen the computable numbers for explicit treatment as involving the least cumbrous technique. I hope shortly to give an account of the relations of the computable numbers, functions, and so forth to one another. This will include a development of the theory of functions of a real variable expressed in terms of com- putable numbers. According to my definition, a number is computable if its decimal can be written down by a machine. image