Синтаксис функции open()
my_file = open(имя_файла [, режим_доступа][, буферизация])
my_file.read([count])
my_file = open("text.txt", encoding='utf-8')
my_string = my_file.read()
print("Было прочитано:")
print(my_string)
my_file.close()
input("Нажмите Enter для выхода")
f = open('text.txt', encoding='utf-8')
for line in f:
print(line)
input("Нажмите Enter для выхода")
print("** Открытие и закрытие файла **")
txt = open("text.txt", "r", encoding='utf-8')
txt.close()
print("** Посимвольное чтение файла **")
txt = open("text.txt", "r")
print(txt.read(1))
print(txt.read(2))
print(txt.read(6))
txt.close()
print("** Посимвольное чтение с указанием кодировки **")
txt = open("text.txt", "r", encoding='utf-8')
print(txt.read(1))
print(txt.read(2))
print(txt.read(6))
txt.close()
print("** Чтение всего файла **")
txt = open("text.txt", "r", encoding='utf-8')
content = txt.read()
print(content)
txt.close()
print("** Читаем строку из файла посимвольно **")
txt = open("text.txt", "r", encoding='utf-8')
print(txt.readline(1))
print(txt.readline(5))
txt.close()
print("** Читаем строку из файла полностью **")
txt = open("text.txt", "r", encoding='utf-8')
print(txt.readline())
print(txt.readline())
txt.close()
print("** Чтение всего файла в список **")
txt = open("text.txt", "r", encoding='utf-8')
lines = txt.readlines()
print(lines)
print(len(lines))
for line in lines:
print(line)
txt.close()
print("** Построчное чтение файла **")
txt = open("text.txt", "r", encoding='utf-8')
for line in txt:
print(line)
txt.close()
input("Нажмите Enter для выхода")
Синтаксис метода write():
my_file.write(string);
my_file = open("primer.txt", "w")
my_file.write("Мне нравится Python!\nЭто классный язык!")
my_file.close()
input("Создание файла и запись завершена!")
my_file = open("primer.txt")
print("Имя файла: ", my_file.name)
print("Файл закрыт: ", my_file.closed)
my_file.close()
print("А теперь закрыт: ", my_file.closed)
input("Нажмите Enter для выхода")
import pickle
import shelve
import pickle
import shelve
first_name = ["Витя", "Максим", "Коля"]
last_name = ["Сидоров", "Петров", "Иванов"]
datafile = open("names.dat", "wb")
pickle.dump(first_name, datafile)
pickle.dump(last_name, datafile)
datafile.close()
input("Файл создан")
import pickle
import shelve
datafile = open("names.dat", "rb")
fnames = pickle.load(datafile)
lnames = pickle.load(datafile)
datafile.close()
print(fnames)
print(lnames)
input()
# Будет выведено:
['Витя', 'Максим', 'Коля']
['Сидоров', 'Петров', 'Иванов']
s = shelve.open("text.dat")
import pickle
import shelve
s = shelve.open("text.dat")
s["first_name"] = ["Витя", "Максим", "Коля"]
s["last_name"] = ["Сидоров", "Петров", "Иванов"]
s.sync()
s.close()
s = shelve.open("text.dat")
print(s["last_name"])
input()