Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

367 строки
11 KiB
Markdown

# Отчет по теме 6
Лыкова Елизавета, А-01-23
## 1. Запуск IDLE, привязка католога, создание файла отчета.
```py
import os
os.chdir("C:\\Users\\Home\\Desktop\\python-labs\\TEMA6")
```
## 2. Вывод данных.
## 2.1 Вывод в командной строке.
```py
stroka='Автоматизированная система управления'
stroka
'Автоматизированная система управления'
```
## 2.2 Вывод с помощью print.
```py
fff=234.5;gg='Значение температуры = '
print(gg,fff)
Значение температуры = 234.5
print(gg,fff,sep='/')
Значение температуры = /234.5
print(gg,fff,sep='/',end='***');print('___')
Значение температуры = /234.5***___
print()
print(""" Здесь может выводиться
большой текст,
занимающий несколько строк""")
Здесь может выводиться
большой текст,
занимающий несколько строк
print("Здесь может выводиться",
"большой текст,",
"занимающий несколько строк")
Здесь может выводиться большой текст, занимающий несколько строк
```
## 2.3 Вывод с использованием write.
```py
import sys
sys.stdout.write('Функция write')
Функция write13
sys.stdout.write('Функция write\n')
Функция write
14
```
## 3. Ввод данных с клавиатуры.
```py
psw=input('Введите пароль:')
Введите пароль:123
psw
'123'
type(psw)
<class 'str'>
while True:
znach = float(input('Задайте коэф.усиления = '))
if znach < 17.5 or znach > 23.8:
print('Ошибка!')
else:
break
Задайте коэф.усиления = 15.4
Ошибка!
Задайте коэф.усиления = 21.6
import math
print(eval(input('введите выражение для расчета = ')))
введите выражение для расчета = math.log10(23/(1+math.exp(-3.24)))
1.34504378689765
```
## 4. Ввод-вывод при работе с файлами.
## 4.1 Путь к файлу.
```py
import os
os.getcwd()
'C:\\Users\\Home\\Desktop\\python-labs\\TEMA6'
Lykova = os.getcwd()
print(Lykova)
C:\Users\Home\Desktop\python-labs\TEMA6
os.mkdir('C:\\Users\\Home\\Desktop\\python-labs\\newdir') #Создает новую директорию.
os.rmdir('C:\\Users\\Home\\Desktop\\python-labs\\newdir') #Удаляет директорию.
os.listdir('C:\\Users\\Home\\Desktop\\python-labs')
['.git', '.gitignore', 'README.md', 'TEMA0', 'TEMA1', 'TEMA2', 'TEMA3', 'TEMA4', 'TEMA5', 'TEMA6', 'TEMA7', 'TEMA8', 'TEMA9']
os.path.isdir('C:\\Users\\Home\\Desktop\\python-labs') #Проверяет, является ли указанный
True
fil = os.path.abspath('OPLATA.dbf')
fil
'C:\\Users\\Home\\Desktop\\python-labs\\TEMA6\\OPLATA.dbf'
drkt = os.path.dirname(fil)
drkt
'C:\\Users\\Home\\Desktop\\python-labs\\TEMA6'
os.path.basename(fil)
'OPLATA.dbf'
os.path.split(fil)
('C:\\Users\\Home\\Desktop\\python-labs\\TEMA6', 'OPLATA.dbf') #Функция отдельно выводит путь к файлу и его наименование.
os.path.exists(fil)
True
fil2 = os.path.abspath('neoplata.dbf')
os.path.exists(fil2)
False
os.path.isfile(fil)
True
os.path.isfile(os.path.dirname(fil)+'fil1.txt')
False
```
## 4.2 Общая схема работы с файлом.
## 4.3 Функция open.
```py
help(open)
Help on built-in function open in module _io:
open(
file,
mode='r',
buffering=-1,
encoding=None,
errors=None,
newline=None,
closefd=True,
opener=None
)
...
========= ===============================================================
Character Meaning
--------- ---------------------------------------------------------------
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' create a new file and open it for writing
'a' open for writing, appending to the end of the file if it exists
'b' binary mode
't' text mode (default)
'+' open a disk file for updating (reading and writing)
========= ===============================================================
The default mode is 'rt' (open for reading text). For binary random
access, the mode 'w+b' opens and truncates the file to 0 bytes, while
'r+b' opens the file without truncation. The 'x' mode implies 'w' and
raises an `FileExistsError` if the file already exists.
...
* On input, if newline is None, universal newlines mode is
enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
these are translated into '\n' before being returned to the
caller. If it is '', universal newline mode is enabled, but line
endings are returned to the caller untranslated. If it has any of
the other legal values, input lines are only terminated by the given
string, and the line ending is returned to the caller untranslated.
* On output, 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.
...
open() returns a file object whose type depends on the mode, and
through which the standard file operations such as reading and writing
are performed. When open() is used to open a file in a text mode ('w',
'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open
a file in a binary mode, the returned class varies: in read binary
mode, it returns a BufferedReader; in write binary and append binary
modes, it returns a BufferedWriter, and in read/write mode, it returns
a BufferedRandom.
It is also possible to use a string or bytearray as a file for both
reading and writing. For strings StringIO can be used like a file
opened in a text mode, and for bytes a BytesIO can be used like a file
opened in a binary mode.
fp=open(file=drkt+'\\zapis1.txt',mode='w')
fp=open(drkt+'\\zapis1.txt','w')
fp=open('zapis1.txt','w')
type(fp)
<class '_io.TextIOWrapper'>
dir(fp)
['_CHUNK_SIZE', '__class__', '__del__', '__delattr__', '__dict__', '__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_checkClosed', '_checkReadable', '_checkSeekable', '_checkWritable', '_finalizing', 'buffer', 'close', 'closed', 'detach', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'line_buffering', 'mode', 'name', 'newlines', 'read', 'readable', 'readline', 'readlines', 'reconfigure', 'seek', 'seekable', 'tell', 'truncate', 'writable', 'write', 'write_through', 'writelines']
```
## 4.4 Закрытие файла.
```py
fp.close()
```
## 4.5 Запись в файл с помощью write.
```py
sps=list(range(1,13))
fp2=open('zapis3.txt','w')
fp2.write(str(sps[:4])+'\n')
13
fp2.write(str(sps[4:8])+'\n')
13
fp2.write(str(sps[8:])+'\n')
16
fp2.close()
```
[Созданный файл](zapis3.txt)
```py
sps3=[['Иванов И.',1],['Петров П.',2],['Сидоров С.',3]]
fp3=open('zapis4.txt','w')
for i in range(len(sps3)):
stroka4=sps3[i][0]+' '+str(sps3[i][1])
fp3.write(stroka4)
fp3.close()
```
[Созданный файл](zapis4.txt)
```py
gh=open('zapis5.txt','w')
for r in sps3:
gh.write(f'{r[0]} {str(r[1])}\n')
gh.close()
```
[Созданный файл](zapis5.txt)
## 4.6 Первый способ чтения информации из текстового файла.
```py
fp = open('zapis3.txt')
for stroka in fp:
stroka = stroka.rstrip('\n')
stroka = stroka.replace('[','')
stroka = stroka.replace(']','')
sps1 = sps1 + stroka.split(',')
fp.close()
sps1
['1', ' 2', ' 3', ' 4', '5', ' 6', ' 7', ' 8', '9', ' 10', ' 11', ' 12']
sps
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
spsnew = [int(i.strip()) for i in sps1]
spsnew
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
```
## 4.7 Метод read.
```py
fp = open('zapis3.txt')
stroka1 = fp.read(12)
stroka2 = fp.read()
fp.close()
print(stroka1)
[1, 2, 3, 4]
print(stroka2)
[5, 6, 7, 8]
[9, 10, 11, 12]
```
## 4.8 Методы readline и readlines.
```py
fp = open('zapis3.txt')
r = fp.readline()
rr = fp.readline()
print(r)
[1, 2, 3, 4]
print(rr)
[5, 6, 7, 8]
fp.close()
fp = open('zapis3.txt')
rrr = fp.readlines()
print(rrr)
['[1, 2, 3, 4]\n', '[5, 6, 7, 8]\n', '[9, 10, 11, 12]\n']
fp.close()
```
## 4.9 Функции модуля pickle.
```py
import pickle
mnoz1={'pen','book','pen','iPhone','table','book'}
fp = open('zapis6.mnz','wb')
pickle.dump(mnoz1,fp)
fp.close()
```
![белиберда](ris1.png)
```py
fp=open('zapis6.mnz','rb')
mnoz2=pickle.load(fp)
fp.close()
mnoz2
{'book', 'iPhone', 'pen', 'table'}
mnoz1 == mnoz2
True
```
Результат ввода mnoz1 и вывода mnoz2 различаются, потому что множество не имеет порядка элементов и их повторений.
```py
fp = open('zapis7.2ob','wb')
pickle.dump(mnoz1,fp)
pickle.dump(sps3,fp)
fp.close()
fp=open('zapis7.2ob','rb')
obj1=pickle.load(fp)
obj2=pickle.load(fp)
fp.close()
print(obj1,obj2)
{'book', 'iPhone', 'pen', 'table'} [['Иванов И.', 1], ['Петров П.', 2], ['Сидоров С.', 3]]
```
## 5. Перенаправление потоков ввода и вывода данных.
```py
import sys
vr_out = sys.stdout
fc = open('Stroka.txt','w')
sys.stdout = fc
print('запись строки в файл')
sys.stdout = vr_out
print('запись строки на экран')
запись строки на экран
fc.close()
```
[Запись в файл](Stroka.txt)
```py
tmp_in = sys.stdin
fd = open("Stroka.txt", "r")
sys.stdin = fd
sys.stdin
<_io.TextIOWrapper name='Stroka.txt' mode='r' encoding='cp1251'>
while True:
try:
line = input()
print(line)
except EOFError:
break
запись строки в файл
fd.close()
sys.stdin = tmp_in
```