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

25 KiB

Отчёт по теме 6

Киреев Юрий А-02-23

1. Запуск интерактивной оболочки IDLE

Создал файл отчёта

2. Вывод данных на экран дисплея

2.1. Вывод в командной строке

Пока ведется работа с инструкциями, содержимое объекта можно увидеть, с помощью упоминания его в командной строке, например:

>>> stroka='Автоматизированная система управления'
>>> stroka
'Автоматизированная система управления'

Этот способ называется «эхо-выводом». Он пригоден при работе в командной строке, однако в пользовательских функциях, которые будут изучаться дальше, этот способ применять нельзя.

2.2. Вывод с использованием функции print

Пример вывода:

>>> fff=234.5;gg='Значение температуры = '
>>> print(gg, fff)   #Можно вывести несколько объектов за одно обращение к функции
Значение температуры =  234.5

Если нужен другой разделитель его можно указать в отдельном аргументе sep, например:

>>> print(gg, fff, sep='/')
Значение температуры = /234.5

После вывода автоматически осуществляется переход на другую строку. Если курсор надо оста-вить в той же строке, то следует использовать еще один аргумент, например:

>>> print(gg, fff,sep='/',end='***'); print('____')
Значение температуры = /234.5***____

Наоборот, если в какой-то момент требуется просто перейти на новую строку, можно использо-вать такое обращение к функции:

>>> print()

Наконец, оператор вывода может располагаться на нескольких строках с использованием тройных кавычек:

>>> print(""" Здесь может выводиться
большой текст,
занимающий несколько строк""")

 Здесь может выводиться
большой текст,
занимающий несколько строк

>>> print("Здесь может выводиться",
     "большой текст,",
     "занимающий несколько строк")
Здесь может выводиться большой текст, занимающий несколько строк

2.3. Вывод с использованием метода write объекта sys.stdout.

Объект stdout представляет собой поток стандартного вывода – объект, в который программы выводят символьное представление данных. Обычно это – экран дисплея. Объект находится в модуле sys, который надо импортировать.

>>> import sys
>>> sys.stdout.write('Функция write')
Функция write13

Если это требуется, то следует в конце строки добавить один или несколько символов “\n”:

>>> sys.stdout.write('Функция write\n')
Функция write
14

3. Ввод данных с клавиатуры

За ввод отвечает функция input:

>>> psw=input('Введите пароль:')
Введите пароль:123
>>> psw
'123'
>>> type(psw)
<class 'str'>

Пример 1. Ввод с контролем значения.

Пусть вводится число, которое должно находиться в интервале значений от 17.5 до 23.8.

>>> while True:
>>> 	znach=float(input('Задайте коэф.усиления = '))
>>> 	if znach<17.5 or znach>23.8:
>>> 		print('Ошибка!')
>>> 	else:
>>> 		break

Задайте коэф.усиления = 15.4
Ошибка!
Задайте коэф.усиления = 21.6
znach
21.6

Пример 2. Ввод и обработка выражения, подлежащего расчету.

import math
print(eval(input('введите выражение для расчета = ')))
введите выражение для расчета = math.log10(23/(1+math.exp(-3.24)))
1.34504378689765

4. Ввод-вывод при работе с файлами.

4.1. Функции для работы с путем к файлу.

Эти функции собраны в модуле os:

>>> import os
>>> os.getcwd()
'C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python310'
>>> KireevYuri = os.getcwd()
>>> print(KireevYuri)
C:\Users\user\AppData\Local\Programs\Python\Python310

Изменить расположение рабочего каталога можно обращением к уже многократно применявшейся функции os.chdir:

>>> os.chdir('C:\\Users\\user\\Desktop\\ПОАС\\python-labs\\TEMA6')

Самостоятельно изучим некоторые функции из модуля:

>>> os.mkdir("new_folder") #создание нового подкаталога
>>> print("Папка 'new_folder' создана")
Папка 'new_folder' создана
>>> os.rmdir("new_folder") #удаление подкаталога
>>> os.listdir() #отображение содержимого папки (в данном случае текущего каталога)
['.gitkeep', 'report.md']
os.path.isdir('C:\\Users\\user\\Desktop\\ПОАС\\python-labs\\TEMA6') #является ли путь директорией
True

Попробуем получить символьную строку, содержащую имя файла вместе с полным путем доступа к нему.

>>> fil=os.path.abspath('Методические указания по ПОАС (4)')
>>> print(fil)
C:\Users\user\Desktop\ПОАС\python-labs\TEMA6\Методические указания по ПОАС (4)

Выделим путь доступа к файлу из строки, содержащей и этот путь, и имя файла с помощью функции os.path.dirname:

>>> drkt=os.path.dirname(fil)
>>> print(drkt)
C:\Users\user\Desktop\ПОАС\python-labs\TEMA6

Наоборот, выделить имя файла из этой строки с отбрасыванием пути можно с помощью функции os.path.basename:

>>> name = os.path.basename(fil); print(name)
Методические указания по ПОАС (4)

Cамостоятельно изучите функцию os.path.split.

>>> sp = os.path.split(fil)
>>> print(sp)
('C:\\Users\\user\\Desktop\\ПОАС\\python-labs\\TEMA6', 'Методические указания по ПОАС (4)')

Проверим, существуют ли заданные пути с помощью функции os.path.exists.

>>> os.path.exists(drkt)
True
>>> os.path.exists('C:\\Users\\user\\Desktop\\ПОАСC')
False

Проверим наличие файла с известным расположением с помощью функции os.path.isfile.

os.path.isfile(fil)
True
os.path.isfile(os.path.dirname(fil)+'fil1.txt')
False

4.2. Общая схема работы с файлом

Для обмена данными с файлом необходимо выполнить следующие операции:

  1. Открытие файла с указанием его имени и цели (чтение, запись, добавление данных);
  2. Выполнение одной или нескольких операций обмена данными с файлом;
  3. Закрытие файла.

4.3. Открытие файла для записи или чтения данных – функция open.

>>> 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)
    Open file and return a stream.  Raise OSError upon failure.
    
    file is either a text or byte string giving the name (and the path
    if the file isn't in the current working directory) of the file to
    be opened or an integer file descriptor of the file to be
    wrapped. (If a file descriptor is given, it is closed when the
    returned I/O object is closed, unless closefd is set to False.)
    
    mode is an optional string that specifies the mode in which the file
    is opened. It defaults to 'r' which means open for reading in text
    mode.  Other common values are 'w' for writing (truncating the file if
    it already exists), 'x' for creating and writing to a new file, and
    'a' for appending (which on some Unix systems, means that all writes
    append to the end of the file regardless of the current seek position).
    In text mode, if encoding is not specified the encoding used is platform
    dependent: locale.getpreferredencoding(False) is called to get the
    current locale encoding. (For reading and writing raw bytes use binary
    mode and leave encoding unspecified.) The available modes are:
    
    ========= ===============================================================
    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)
    'U'       universal newline mode (deprecated)
    ========= ===============================================================
    
    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.
    
    Python distinguishes between files opened in binary and text modes,
    even when the underlying operating system doesn't. Files opened in
    binary mode (appending 'b' to the mode argument) return contents as
    bytes objects without any decoding. In text mode (the default, or when
    't' is appended to the mode argument), the contents of the file are
    returned as strings, the bytes having been first decoded using a
    platform-dependent encoding or using the specified encoding if given.
    
    'U' mode is deprecated and will raise an exception in future versions
    of Python.  It has no effect in Python 3.  Use newline to control
    universal newlines mode.
    
    buffering is an optional integer used to set the buffering policy.
    Pass 0 to switch buffering off (only allowed in binary mode), 1 to select
    line buffering (only usable in text mode), and an integer > 1 to indicate
    the size of a fixed-size chunk buffer.  When no buffering argument is
    given, the default buffering policy works as follows:
    
    * Binary files are buffered in fixed-size chunks; the size of the buffer
      is chosen using a heuristic trying to determine the underlying device's
      "block size" and falling back on `io.DEFAULT_BUFFER_SIZE`.
      On many systems, the buffer will typically be 4096 or 8192 bytes long.
    
    * "Interactive" text files (files for which isatty() returns True)
      use line buffering.  Other text files use the policy described above
      for binary files.
    
    encoding is the name of the encoding used to decode or encode the
    file. This should only be used in text mode. The default encoding is
    platform dependent, but any encoding supported by Python can be
    passed.  See the codecs module for the list of supported encodings.
    
    errors is an optional string that specifies how encoding errors are to
    be handled---this argument should not be used in binary mode. Pass
    'strict' to raise a ValueError exception if there is an encoding error
    (the default of None has the same effect), or pass 'ignore' to ignore
    errors. (Note that ignoring encoding errors can lead to data loss.)
    See the documentation for codecs.register or run 'help(codecs.Codec)'
    for a list of the permitted encoding error strings.
    
    newline controls how universal newlines works (it only applies to text
    mode). It can be None, '', '\n', '\r', and '\r\n'.  It works as
    follows:
    
    * 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.
    
    If closefd is False, the underlying file descriptor will be kept open
    when the file is closed. This does not work when a file name is given
    and must be True in that case.
    
    A custom opener can be used by passing a callable as *opener*. The
    underlying file descriptor for the file object is then obtained by
    calling *opener* with (*file*, *flags*). *opener* must return an open
    file descriptor (passing os.open as *opener* results in functionality
    similar to passing None).
    
    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.

Откройте файл zapis1.txt для записи данных с помощью инструкции:

>>> fp=open(file=drkt+'\\zapis1.txt',mode='w') #в рабочем каталоге был создан файл zapis1.txt

Вообще говоря, аргументы функции с их именами могут располагаться в любом порядке. Если имя файла располагается на месте первого аргумента, а цель использования – на втором, то имена аргументов можно не указывать и просто вводить.

>>> fp=open(drkt+'\\zapis1.txt','w')

Если путь в переменной drkt совпадает с рабочим каталогом, то его можно опустить, оставив только имя открываемого файла:

>>> fp=open('zapis1.txt','w')

Создаваемые и читаемые файлы могут быть бинарными или символьными. При открытии бинарного файла к указанным выше буквам в аргументе-цели надо добавить символ «b». Например:

fp1=open(drkt+'\\zapis2.bin',mode='wb+') #был создан бинарный файл zapis2.bin в рабочем каталоге.

4.4. Закрытие файла

Сразу после завершения работы с файлом его следует закрыть для обеспечения сохранности его содержимого. Это делается с помощью метода close, применяемого к объекту – файловой пе-ременной. Например:

>>> fp.close()

4.5. Запись информации в файл с помощью метода write

Метод write относится к объекту – файловой переменной. Пример: Cоздадим список с элементами-числами от 1 до 12 и запишем их в файл по 4 числа на строке:

>>> 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:

[1, 2, 3, 4]
[5, 6, 7, 8]
[9, 10, 11, 12]

Создадим список с элементами-списками и пусть его элементы требуется построчно записать в файл zapis4.txt.

>>> 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)

11
11
12
>>> fp3.close()

Что произошло в файле:

Иванов И. 1Петров П. 2Сидоров С. 3

Легко заметить, что информация записана в файл не очень удачно. Попробуем иначе.

>>> gh=open('zapis5.txt','w')
                                                          
>>> for r in sps3:
>>>     gh.write(r[0]+' '+str(r[1])+'\n')

12
12
13
>>> gh.close()

Посмотрим на то, что получилось:

Иванов И. 1
Петров П. 2
Сидоров С. 3

Этот цикл также можно представить одной строкой

>>> gh=open('zapis5.txt','w')                                                          
>>> for r in sps3: gh.write(r[0]+' '+str(r[1])+'\n')

                                                          
12
12
13
>>> gh.close()

В файле ничего не изменилось.

4.6. Первый способ чтения информации из текстового файла.

Прочитаем информацию из ранее созданного файла zapis3.txt.

>>> sps1=[]                                                      
>>> fp=open('zapis3.txt')                                                    
>>> for stroka in fp:
>>> 	stroka=stroka.rstrip('\n')
>>> 	stroka=stroka.replace('[','')
>>>	stroka=stroka.replace(']','')
>>> 	sps1=sps1+stroka.split(',')
>>> fp.close()
>>> print(sps1)
                                                          
['1', ' 2', ' 3', ' 4', '5', ' 6', ' 7', ' 8', '9', ' 10', ' 11', ' 12']

Прочитанные данные несколько отличаются от исходных. Исправить это можно так:

>>> sps2 = []
>>> fp = open('zapis3.txt')
>>> for stroka in fp:
>>>     stroka = stroka.rstrip('\n')
>>>     stroka = stroka.replace('[', '')
>>>     stroka = stroka.replace(']', '')
>>>     stroka = stroka.replace(' ', '')
>>>     sps2 = sps2 + [int(x) for x in stroka.split(',')]    
>>> fp.close()
>>> sps2
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

4.7. Чтение информации с помощью метода read.

Метод read, также как и write, относится к объекту - файловой переменной.

>>> fp = open("zapis3.txt")
>>> stroka1 = fp.read(12) # Чтение первых 12 байт (символов)
>>> stroka2 = fp.read() # Чтение файла полностью
>>> fp.close()
>>> stroka1
    '[1, 2, 3, 4]'
>>> stroka2
    '\n[5, 6, 7, 8]\n[9, 10, 11, 12]\n'
>>> fp.close()

4.8. Чтение информации с помощью методов readline и readlines.

Методы readline и readlines позволяют прочитать одну или несколько строк символов соответственно. (Чтение происходит с текущего положения маркера)

>>> fp = open("zapis3.txt")
>>> stroka1 = fp.readline() # Чтение первой строки файла
>>> stroka2 = fp.readline() # Чтение второй строки файла
>>> fp.close()
>>> fp = open("zapis3.txt")
>>> stroka3 = fp.readlines() # Чтение всех строк файла
>>> fp.close()
>>> stroka1
'[1, 2, 3, 4]\n'
>>> stroka2
'[5, 6, 7, 8]\n'
>>> stroka3
['[1, 2, 3, 4]\n', '[5, 6, 7, 8]\n', '[9, 10, 11, 12]\n']

4.9. Ввод-вывод объектов с использованием функции из модуля pickle.

Для работы с бинарными файлами можно пользоваться функциями из модуля pickle. Примером этого может послужить запись объекта-множества в бинарный файл:

>>> import pickle
>>> mnoz1 = {"pen", "book", "pen", "iPhone", "table", "book"}
>>> fp = open("zapis6.mnz", "wb")
>>> pickle.dump(mnoz1, fp) # Запись объекта в файл
>>> fp.close()

Содержимое файла:

Ђ#       Џ”(Њpen”ЊiPhone”Њbook”Њtable”ђ.

Получение объекта из файла можно осуществить с помощью метода load:

>>> fp = open("zapis6.mnz", "rb")
>>> mnoz2 = pickle.load(fp) # Получение объекта из файла
>>> fp.close()
>>> mnoz2
{'book', 'iPhone', 'table', 'pen'}
>>> mnoz1 == mnoz2
True

Важно подметить, что при считывании из файла объекты имеют тот же порядок, что и при их записи в него:

>>> fp = open("zapis7.2ob", "wb")
>>> pickle.dump(mnoz1, fp)
>>> pickle.dump(sps3, fp)
>>> fp.close()
>>> fp = open("zapis7.2ob", "rb")
>>> obj1 = pickle.load(fp) # Первое обращение к load читает первый объект
>>> obj2 = pickle.load(fp) # Второе – читает второй
>>> fp.close()
>>> obj1
{'book', 'iPhone', 'table', 'pen'}
>>> obj2
[['Иванов И.', 1], ['Петров П.', 2], ['Сидоров С.', 3]]
## 5. Перенаправление потоков ввода и вывода данных.
Потоки ввода-вывода можно перенаправлять, например в файл:
```py
>>> import sys
>>> vr_out = sys.stdout # Запоминаем текущий поток вывода
>>> fc = open("Stroka.txt", "w") # Откроем файл вывода
>>> sys.stdout = fc # Перенацеливаем стандартный поток вывода на файл
>>> print("запись строки в файл") # Вывод теперь будет не на экран, а в файл
>>> fc.close()
>>> sys.stdout = vr_out # Восстановление текущего потока
>>> print('запись строки на экран')  #Убеждаемся, что вывод на экран восстановился
    запись строки на экран

В результате данных действий строка "Запись строки в файл" записалась в файл Stroka.txt:

запись строки в файл

Аналогичную операцию можно провести и для потока ввода sys.stdin – вместо клавиатуры – из файла:

>>> 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 # Не забыть вернуть стандартное назначение для потока ввода

6. Завершение работы со средой.