Технологии программирования. Работа с файлами

Слайд 2

Открытие и закрытие файлов

При работе с файлами необходимо соблюдать некоторую последовательность операций:
Открытие

Открытие и закрытие файлов При работе с файлами необходимо соблюдать некоторую последовательность
файла с помощью метода open()
Чтение файла с помощью метода read() или запись в файл посредством метода write()
Закрытие файла методом close()

Слайд 3

open(file, mode)

C://somedir/somefile.txt

somedir/somefile.txt

r (Read). Файл открывается для чтения. Если файл не найден, то

open(file, mode) C://somedir/somefile.txt somedir/somefile.txt r (Read). Файл открывается для чтения. Если файл
генерируется исключение FileNotFoundError
w (Write). Файл открывается для записи. Если файл отсутствует, то он создается. Если подобный файл уже есть, то он создается заново, и соответственно старые данные в нем стираются.
a (Append). Файл открывается для дозаписи. Если файл отсутствует, то он создается. Если подобный файл уже есть, то данные записываются в его конец.
b (Binary). Используется для работы с бинарными файлами. Применяется вместе с другими режимами - w или r.

Слайд 4

myfile = open("hello.txt", "w")
myfile.close()

try:
    somefile = open("hello.txt", "w")
    try:
        somefile.write("hello world")
    except Exception as e:
        print(e)
    finally:
        somefile.close()
except Exception

myfile = open("hello.txt", "w") myfile.close() try: somefile = open("hello.txt", "w") try: somefile.write("hello
as ex:
    print(ex)

Слайд 5

with open(file, mode) as file_obj:
    инструкции

with open("hello.txt", "w") as somefile:
    somefile.write("hello world")

with open(file, mode) as file_obj: инструкции with open("hello.txt", "w") as somefile: somefile.write("hello world")

Слайд 6

Текстовые файлы

with open("hello.txt", "w") as file:
    file.write("hello world")

with open("hello.txt", "a") as file:
    file.write("\ngood bye,

Текстовые файлы with open("hello.txt", "w") as file: file.write("hello world") with open("hello.txt", "a")
world")

hello world
good bye, world

Слайд 7

with open("hello.txt", "a") as hello_file:
    print("Hello, world", file=hello_file)

with open("hello.txt", "a") as hello_file: print("Hello, world", file=hello_file)

Слайд 8

Чтение файла

readline(): считывает одну строку из файла
read(): считывает все содержимое файла в

Чтение файла readline(): считывает одну строку из файла read(): считывает все содержимое
одну строку
readlines(): считывает все строки файла в список

with open("hello.txt", "r") as file:
    for line in file:
        print(line, end="")

Слайд 9

with open("hello.txt", "r") as file:
    str1 = file.readline()
    print(str1, end="")
    str2 = file.readline()
    print(str2)

hello world
good

with open("hello.txt", "r") as file: str1 = file.readline() print(str1, end="") str2 =
bye, world

Слайд 10

with open("hello.txt", "r") as file:
    line = file.readline()
    while line:
        print(line, end="")
        line = file.readline()

with open("hello.txt",

with open("hello.txt", "r") as file: line = file.readline() while line: print(line, end="")
"r") as file:
    content = file.read()
    print(content)
Имя файла: Технологии-программирования.-Работа-с-файлами.pptx
Количество просмотров: 30
Количество скачиваний: 0