- Модуль IO в Python
- Класс Python BytesIO
- Класс Python StringIO
- Чтение из буфера StringIO
- Чтение файла с помощью io
- Сравнение io.open() и os.open()
- Python io — BytesIO, StringIO
- Python IO Module
- Python BytesIO
- Python StringIO
- Reading using StringIO
- Reading file using StringIO
- io.open() vs os.open()
- Conclusion
- Python BufferedReader
- Working of BufferedReader in Python
- Examples of Python BufferedReader
- Example #1
- Example #2
- Recommended Articles
Модуль IO в Python
Модуль IO очень полезен, когда вы хотите выполнять операции ввода-вывода, связанные с файлами (например, чтение / запись файлов).
Хотя вы можете использовать обычные методы read() и write() для чтения или записи в файл, но этот модуль дает нам гораздо больше гибкости в отношении этих операций.
Этот модуль является частью стандартной библиотеки, поэтому нет необходимости устанавливать его отдельно с помощью pip.
Чтобы импортировать модуль io, мы можем сделать следующее:
В модуле io есть 2 общих класса, которые нам очень пригодятся:
- BytesIO -> операции ввода-вывода с байтовыми данными;
- StringIO -> операции ввода-вывода для строковых данных.
Мы можем получить доступ к этим классам с помощью io.BytesIO и io.StringIO .
Класс Python BytesIO
Здесь мы можем хранить наши данные в виде байтов ( b» ). Когда мы используем io.BytesIO , данные хранятся в буфере в памяти.
Мы можем получить экземпляр байтового потока с помощью конструктора:
import io bytes_stream = io.BytesIO(b'Hello from Journaldev\x0AHow are you?')
Обратите внимание, что мы передаем байтовую строку (с префиксом b ).
Прямо сейчас bytes_stream — это просто дескриптор байтового потока.
Чтобы напечатать данные внутри буфера, нам нужно использовать bytes_stream.getvalue() .
import io bytes_stream = io.BytesIO(b'Hello from Journaldev\x0AHow are you?') print(bytes_stream.getvalue())
Здесь getvalue() берет значение байтовой строки из дескриптора.
Поскольку байтовая строка \x0A является представлением ASCII новой строки (‘\ n’), мы получаем следующий вывод:
b'Hello from Journaldev\nHow are you?'
Теперь всегда рекомендуется закрывать дескриптор буфера после того, как мы закончили свою работу. Это также необходимо для того, чтобы освободить всю память, выделенную для буфера.
Чтобы закрыть буфер, используйте:
Класс Python StringIO
Класс io.StringIO может читать данные, относящиеся к строке, из буфера StringIO.
import io string_stream = io.StringIO("Hello from Journaldev\nHow are you?")
Мы можем читать из строкового буфера с помощью string_stream.read() и писать с помощью string_stream.write() .
Мы можем распечатать содержимое с помощью getvalue() .
import io string_stream = io.StringIO("Hello from Journaldev\nHow are you?") # Print old content of buffer print(f'Initially, buffer: ') # Write to the StringIO buffer string_stream.write('This will overwrite the old content of the buffer if the length of this string exceeds the old content') print(f'Finally, buffer: ') # Close the buffer string_stream.close()
Initially, buffer: Hello from Journaldev How are you? Finally, buffer: This will overwrite the old content of the buffer if the length of this string exceeds the old content
Поскольку мы пишем в тот же буфер, новое содержимое, очевидно, перезапишет старое.
Чтение из буфера StringIO
Подобно записи, мы также можем читать из буфера buffer.read() используя buffer.read() .
import io input = io.StringIO('This goes into the read buffer.') print(input.read())
This goes into the read buffer.
Как видите, содержимое теперь находится внутри буфера чтения, который печатается с помощью buffer.read() .
Чтение файла с помощью io
Мы также можем использовать метод io.open() для прямого чтения из файла, аналогично чтению из файлового объекта.
Здесь этот модуль дает нам возможность выбора между буферизованным и небуферизованным чтением.
Например, следующее будет использовать буферизованное чтение для чтения файла, установив buffering = SIZE . Если SIZE = 0, буферизации не будет.
Предположим, sample.txt имеет следующее содержимое:
Hello from JournalDev! How are you? This is the last line.
import io # Read from a text file in binary format using io.open() # We read / write using a buffer size of 5 bytes file = io.open("sample.txt", "rb", buffering = 5) print(file.read()) # Close the file file.close()
b'Hello from JournalDev!\nHow are you?\nThis is the last line.\n'
Как видите, файл прочитан успешно. Здесь io прочитает файл, используя буфер размером примерно 5 байт.
Сравнение io.open() и os.open()
Функция io.open() — наиболее предпочтительный способ выполнения операций ввода-вывода, поскольку она выполнена как высокоуровневый интерфейс Pythonic.
Напротив, os.open() выполнит системный вызов функции open() . Это вернет дескриптор файла, который нельзя использовать как объект дескриптора io .
Поскольку io.open() является функцией-оболочкой для os.open() , обычно рекомендуется использовать такие функции-оболочки, поскольку они автоматически обрабатывают многие ошибки за вас.
Python io — BytesIO, StringIO
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Python io module allows us to manage the file-related input and output operations. The advantage of using the IO module is that the classes and functions available allows us to extend the functionality to enable writing to the Unicode data.
Python IO Module
There are many ways in which we can use the io module to perform stream and buffer operations in Python. We will demonstrate a lot of examples here to prove the point. Let’s get started.
Python BytesIO
Just like what we do with variables, data can be kept as bytes in an in-memory buffer when we use the io module’s Byte IO operations. Here is a sample program to demonstrate this:
import io stream_str = io.BytesIO(b"JournalDev Python: \x00\x01") print(stream_str.getvalue())
Let’s see the output for this program: The getvalue() function just takes the value from the Buffer as a String.
Python StringIO
We can even use StringIO as well which is extremely similar in use to BytesIO . Here is a sample program:
import io data = io.StringIO() data.write('JournalDev: ') print('Python.', file=data) print(data.getvalue()) data.close()
Let’s see the output for this program: Notice that we even closed the buffer after we’re done with the buffer. This helps save buffer memory as they store data in-memory. Also, we used the print method with an optional argument to specify an IO stream of the variable, which is perfectly compatible with a print statement.
Reading using StringIO
Once we write some data to the StringIO buffer, we can read it as well. Let’s look at a code snippet:
import io input = io.StringIO('This goes into the read buffer.') print(input.read())
Let’s see the output for this program:
Reading file using StringIO
It is also possible to read a file and stream it over a network as Bytes. The io module can be used to convert a media file like an image to be converted to bytes. Here is a sample program:
import io file = io.open("whale.png", "rb", buffering = 0) print(file.read())
Let’s see the output for this program: For this program to run, we had a whale.png image present in our current directory.
io.open() vs os.open()
The io.open() function is a much preferred way to perform I/O operations as it is made as a high-level interface to peform file I/O. It wraps the OS-level file descriptor in an object which we can use to access the file in a Pythonic way. The os.open() function takes care of the lower-level POSIX syscall. It takes input POSIX based arguments and returns a file descriptor which represents the opened file. It does not return a file object; the returned value will not have read() or write() functions. Overall, io.open() function is just a wrapper over os.open() function. The os.open() function just also sets default config like flags and mode too while io.open() doesn’t to it and depends on the values passed to it.
Conclusion
In this lesson, we studied simple operations of python IO module and how we can manage the Unicode characters with BytesIO as well. However, if you are looking for complete file operations such as delete and copy a file then read python read file. Reference: API Doc
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us
Python BufferedReader
The following article provides an outline for Python BufferedReader. It retrieves data from a source and stores it in an internal memory queue. This allows subsequent read operations to efficiently retrieve data from the buffered queue instead of directly accessing the underlying reader stream. The buffered reader class consists of three methods, namely _init_(Reader_in) method, _init_(Reader_in, iBufSize) method, and newline() method.
BufferedReader(inputstream, buffer_size=DEFAULT_BUFFER_SIZE)
- inputstream is the input stream from which the data must be read.
- buffer_size is the size of the buffer which is set to the default size represented by DEFAULT_BUFFER_SIZE.
Working of BufferedReader in Python
- The Buffered Reader class provides input buffering to the reader stream.
- The Buffered Reader class derives from its base class, BufferedIOBase, to utilize its functionality and properties.
- The buffered reader class consists of three methods, namely _init_(Reader_in) method, _init_(Reader_in, iBufSize) method, and newline() method.
- The __init__(Reader_in) method is utilized to instantiate an object of the BufferedReader class, which receives the given input stream as a parameter.
- The readline() method retrieves data from the input stream. It reads a line of data from the stream and returns it as a string.
Examples of Python BufferedReader
Given below are the examples mentioned :
Example #1
Python program to demonstrate a buffered reader to read the file’s contents.
#a module called sys in python is imported import sys #a module called io in python is imported import io #a variable sourcefile is used to store the argument that is passed while running the script. Sys.argv is the argument taking the file name while executing the script and 1 indicates the argument number while 0 being the script that we are executing. sourcefile = sys.argv[1] #the file is opened in binary mode to read using open function with open(sourcefile, 'rb') as file: #file descriptor is obtained by making using of FileIO which is used to identify the file that is opened fi = io.FileIO(file.fileno()) #Buffered reader is then used to read the contents of the file fb = io.BufferedReader(fi) #the contents of the file is printed print fb.read(20)
This module allows access to system-specific parameters and functions. Sys. argv is the argument taking the file name while executing the script, 1 indicates the argument number, and 0 is the script we execute. The program opens the file in binary mode using the open function to enable reading from it. It obtains a file descriptor by creating a FileIO object, which identifies the opened file. Then, it uses a BufferedReader to read the contents of the file. Finally, it prints the contents of the file.
Example #2
Python program to demonstrate a buffered reader to read the file’s contents.
#a module called sys in python is imported import sys #a module called io in python is imported import io #a variable filename is used to store the argument that is passed while running the script. Sys.argv is the argument taking the file name while executing the script script and 1 indicates the argument number while 0 being the script that we are executing. filename = sys.argv[1] #the file is opened in binary mode to read using open function with open(filename, 'rb') as file: #file descriptor is obtained by making using of FileIO which is used to identify the file that is opened fi = io.FileIO(file.fileno()) #Buffered reader is then used to read the contents of the file fb = io.BufferedReader(fi) #the contents of the file is printed print fb.read(20)
Sys.argv is the argument taking the file name while executing the script, and 1 indicates the argument number, while 0 is the script we execute. The program opens the file in binary mode using the open function to read it. It obtains a file descriptor by creating a FileIO object, which identifies the open file. Then, it uses a BufferedReader to read the contents of the file. Finally, it prints the contents of the file.
Recommended Articles
This is a guide to Python BufferedReader. Here we discuss the introduction to Python BufferedReader, along with working and programming examples. You may also have a look at the following articles to learn more –