Files
learning/python/файлы/файлы.py
2022-05-06 00:49:26 +03:00

84 lines
2.2 KiB
Python
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#создание файлов. w - write
text_file = open('data_file.txt', 'w')
#Запись в файл
text_file.write('Hello\n')
text_file.write('World')
#Закрытие файла
text_file.close()
#По умолчанию файлы открываются в режиме r - read
text_file = open('data_file.txt')
#Чтение из файла. (в скобках можно указать кол-во символов для чтения)
print(text_file.read())
print('\n')
#Чтение одной строки. (в скобках можно указать кол-во символов для чтения)
text_file = open('data_file.txt')
S = text_file.readline()
S = text_file.readline()
print(S)
print('\n')
#Чтение файла в список строк
text_file = open('data_file.txt')
L = text_file.readlines()
print(L)
print('\n')
#Запись строк из списка в файл
text_file = open('data_file.txt', 'w')
tmp_list = ['spam\n', 'egg\n', 'Italia']
text_file.writelines(tmp_list)
text_file = open('data_file.txt')
print(text_file.read())
print('\n****************')
#Итератор файла
text_file = open('data_file.txt')
for S in text_file:
print(S * 2)
print('****************\n')
#Изменяет текущую позицию в файле для следующей операции, смещая ее на N байтов от начала файла.
text_file = open('data_file.txt')
text_file.seek(7)
print(text_file.read())
print('\n')
#Запись объектов
objects = open('objects.txt', 'w')
L = [1, 5, 10]
X, Y, Z = 41, 42, 43
D = {'food': 'spam', 'tool': 'wrench'}
objects.write('{0},{1},{2}\n'.format(X, Y, Z))
objects.write(str(L) + '&' + str(D) + '\n')
objects = open('objects.txt')
print(objects.read())
#Чтение объектов
objects = open('objects.txt')
line = objects.readline()
#Удаление символа конца строки
line = line.rstrip()
print(line)
numbers = line.split(',')
L = [int(x) for x in numbers]
print(L)
line = objects.readline()
line = line.rstrip()
elements = line.split('&')
result = [eval(x) for x in elements]
print(result)