Module io. Class hierarchy. Class io.IOBase. Methods for working with IOBase class files
Before exploring this topic, it is recommended that you familiarize yourself with the following topic:
Contents
- 1. Module io. The purpose. Input/output types
- 2. Class hierarchy of input/output streams
- 3. Class io.IOBase
- 4. Methods of Io.IOBase class
- 4.1. The close() method. File closing
- 4.2. Property closed. Determining if a file is open
- 4.3. Method fileno(). Get file descriptor
- 4.4. Method flush(). Buffer clearing
- 4.5. Method isatty(). Definition of interactive file stream
- 4.6. Method readable(). Determine, if file stream can be read
- 4.7 Method readline(). Reading a line from a file
- 4.8. Method readlines(). Read all lines from a file
- 4.9. Method seek(). Positioning the read/write pointer by a specified number of bytes
- 4.10. Method seekable(). Definition of random access support
- 4.11. Method tell(). Return the current position of the read/write pointer
- 4.12. Method truncate(). Resize file
- 4.13. Method writable(). Determine, if file stream supports writing
- 4.14. Method writelines(). Writing a list of lines to a file
- Related topics
Search other websites:
1. Module io. The purpose. Input/output types
The io module provides tools for working with various types of input/output. Python provides 3 main types of I/O:
- text input/output – provides work with string objects of type str;
- binary input/output – provides work with binary objects of type bytes;
- direct input/output (raw input/output).
A file object (current object) is created for any type of input/output.
⇑
2. Class hierarchy of input/output streams
Figure 1 shows the hierarchy of I/O classes. At the top of the hierarchy is the abstract IOBase class.
Figure 1. The hierarchy of input/output classes
⇑
3. Class io.IOBase
The abstract IOBase class is described in the io module. This class is the base class in the hierarchy of I/O classes (see Figure 1). The class declares basic methods and properties, some of which are overridden in the inherited classes BufferedIOBase, TextIOBase, RawIOBase.
By default, the class implements a file that can be read, written, or found. If the file operation is not supported, the io.IOBase class provides the use of ValueError or UnsupportedOperation exceptions. If you try to call methods for a closed file, an exception of type ValueError is generated. The presentation of the resulting strings is different for text and binary files.
⇑
4. Methods of Io.IOBase class
4.1. The close() method. File closing
The close() method implements closing the file. After calling close(), the stream associated with the file is cleared and closed. This method has no effect if the file is already closed. That is, the second, third, etc. calling close() on a closed file will have no effect.
If the file is closed, then any operation of reading the file or writing to the file will raise a ValueError exception.
Example.
# Python. Working with Files # Method close() # 1. Open text file for reading f1 = open('myfile1.txt', 'rt') # Processing data in a file # ... # Close the file using close () f1.close() # 2. Open binary file for writing f2 = open('myfile2.bin', 'wb') # Write data to the file # ... # Close the binary file f2.close()
⇑
4.2. Property closed. Determining if a file is open
If the file stream is currently open, then closed = False. If the file (stream) is closed, then closed = True.
Example.
# Property closed # 1. Open text file for reading f1 = open('myfile1.txt', 'rt') # Print the value of closed if f1.closed: print("File \'myfile1.txt\' is closed") else: print("File 'myfile1.txt' is opened") # Close the file using close() f1.close() # Display closed value again if f1.closed: print("File \'myfile1.txt\' is closed") else: print("File 'myfile1.txt' is opened")
Program result
File 'myfile1.txt' is opened File 'myfile1.txt' is closed
⇑
4.3. Method fileno(). Get file descriptor
The fileno() method returns the main file descriptor, which has an integer value (if one exists). If the file object does not use a descriptor, an OSError is returned.
Example.
# Method fileno() # 1. Open text file for reading f1 = open('myfile1.txt', 'rt') # 2. Open binary file for reading f2 = open('myfile1.bin', 'rb') # 3. Print the handle that is associated with the object f1 d1 = f1.fileno() print("f1.fileno() = ", d1) # 4. Print the handle that is associated with the object f2 d2 = f2.fileno() print("f2.fileno() = ", d2) # 5. Close the files f1.close() f2.close()
Program result
f1.fileno() = 3 f2.fileno() = 4
⇑
4.4. Method flush(). Buffer clearing
The flush() method flushes the stream writing buffers where they can be applied. The buffer is flushed in one of two ways:
- if the file is being closed by the close() method;
- if you need to push the data out of the buffer without closing the file using the flush() method.
Example.
# Method flush(). Clearing the buffer # 1. Open text file for reading f1 = open('myfile1.txt', 'rt') # Read the file f1 completely, # the result in an array of lines Lines Lines = f1.readlines() # Display Lines for item in Lines: print(item) # Clear the buffer f1.flush() # Close the file f1.close()
Program result
#include <iostream.h> using namespace std; void main() { cout << "Hello world!" << endl; }
⇑
4.5. Method isatty(). Definition of interactive file stream
The isatty() method allows you to determine if a file stream is interactive, that is, it is obtained from a terminal or a tty-device.
# Method isatty() # 1. Open text file for reading f1 = open('myfile1.txt', 'rt') # 2. Determine if there is an interactive stream, # that is associated with f1 if f1.isatty(): print('The stream f1 is interactive.') else: print('The stream f1 is not interactive') f1.close()
Program result
The stream f1 is not interactive
⇑
4.6. Method readable(). Determine, if file stream can be read
# Method readable() - determines whether a file stream can be read # 1. Open text file for reading f1 = open('myfile1.txt', 'rt') # 2. Check whether the file can be read if f1.readable(): # if possible, read the entire file s = f1.read() # display a message that the file has been read print("File is read.") else: print("Cannot read the file.") f1.close()
Program result
File is read.
⇑
4.7 Method readline(). Reading a line from a file
The readline() method returns a string from a file. The string is represented by a sequence of bytes that ends with the character ‘\n’. If the end of the file is reached, then readline() returns an empty string. According to the Python documentation, the general form of using the method is as follows:
s = readline(size=-1)
where
- s – the line, that read from the file;
- size – sets the maximum number of bytes that can be read at a time.
Example. The example demonstrates reading a text file.
# Python. Work with files # Method readline() # Read a text file and display it # 1. Open the file in text mode f1 = open('myfile1.txt', 'r') # 2. Lines reading cycle print("Content of file \'myfile1.txt\'") print() s = f1.readline() # method readline() # empty string '' means the end of the file while s!='': print(s) s = f1.readline() # method readline() f1.close()
The result of the program. The contents of the file are displayed (C++ program that displays “Hello world!” On the screen).
Content of file 'myfile1.txt' #include <iostream.h> using namespace std; void main() { cout << "Hello world!" << endl; }
⇑
4.8. Method readlines(). Read all lines from a file
The readlines() method allows you to read and return a list of lines from a file stream. In accordance with the documentation, the general form of the method is as follows:
strings = readlines(hint = -1)
where
- strings – list of read lines. Lines are separated based on the newline character ‘\n’;
- hint – tooltip that sets the maximum possible size of all read lines. In other words, such a number of lines are read, the total length of which does not exceed hint.
Example.
# Method readlines() - reading lines from a file # 1. Read all lines from a file # 1.1. Open text file for reading f1 = open('myfile1.txt', 'rt') # 1.2. Read strings strings = f1.readlines() # 1.3. Display strings print("The content of file 'myfile1.txt'.") # Display number of rows in the file print("Number of lines in file: ", len(strings)) print() # Print file contents line by line for s in strings: # remove extra character '\n' in lines s = s.rstrip() print(s) # 1.4. Close the file f1.close() # ---------------------------------------------- # 2. Method readlines() - read a limited number of lines from a file # 2.1. Open file for reading f1 = open('myfile1.txt', 'rt') # 2.2. Read a limited number of lines whose bytes do not exceed 50 strings2 = f1.readlines(50) # 2.3. Close the file f1.close() # 2.4. Display strings2 print("----------------------------------") print("List strings2:") print() for s in strings2: s = s.rstrip() # убрать '\n' print(s)
Program result
The content of file 'myfile1.txt'. Number of lines in file: 7 #include <iostream.h> using namespace std; void main() { cout << "Hello world!" << endl; } ---------------------------------- List strings2: #include <iostream.h> using namespace std; void main()
⇑
4.9. Method seek(). Positioning the read/write pointer by a specified number of bytes
The seek() method is used to change the position of the stream by a specified value. The change is specified in bytes. According to the Python documentation, the general form of using the method is as follows:
p = f.seek(offset[, whence])
here
- f – file object;
- p – absolute position in the file;
- offset – an integer value equal to the number of bytes to move the pointer to. For example, if offset = 3, then the pointer is shifted by 3 bytes to the end of the file. If offset = -2, then the pointer is shifted 2 bytes to the beginning of the file;
- whence – determines the set of values that offset can take. whence parameter can take one of three values:
- whence = SET_SEEK or whence = 0 (default value) – specifies the beginning of the stream. In this case, offset is set to the range of possible values offset>=0.
- whence = SET_CUR of whence = 1 – determines the current position of the stream. In this case, offset can be positive and negative.
- whence = SET_END or whence = 2 – end of stream. Typically, the offset value is negative.
Example.
# Method seek() - shift the read pointer by the specified number of bytes # 1. Write the string 'abcdefghijklmnop' to the file f1 = open('myfile10.txt', 'wt') f1.write('abcdefghijklmnop') # 2. close the file f1.close() # 3. Open file for reading f1 = open('myfile10.txt', 'rt') # 4. Read the word 'def' from the file # 4.1. Move pointer to 'd' p = f1.seek(3, 0) # p - current new position print("p = ", p) # p = 3 # 4.2. Read 3 characters per line s = f1.readline(3) # s = 'def' print("s = ", s) # 5. Move the pointer to the beginning of the file p2 = f1.seek(0, 0) # p2 = 0 print("p2 = ", p2) # 5. Move the pointer to the end of the file p3 = f1.seek(0, 2) print("p3 = ", p3) # p3 = 16 - absolute position f1.close()
Program result
p = 3 s = def p2 = 0 p3 = 16
⇑
4.10. Method seekable(). Definition of random access support
The seekable() method determines whether the file stream supports random access, which involves the use of the seek(), tell(), truncate() functions. The general form of using the method is as follows
res = f.seekable()
where
- f – file object;
- res – result (True or False). If res = True, then the file that is associated with the file object f supports random access. If res = False, then an attempt to use the seek(), tell(), truncate() functions will throw an OSError exception.
Example.
# Method seekable() - check if a file supports random access # 1. Binary file f2 = open('myfile2.bin', 'rb') if (f2.seekable()): print('File "myfile2.bin". Random access = True') else: print('File "myfile2.bin". Random access = False') f2.close() # 2. Text file f1 = open('myfile1.txt', 'rt') if (f1.seekable()): print('File "myfile2.txt". Random access = True') else: print('File "myfile2.txt". Random access = False') f1.close()
Program result
File "myfile2.bin". Random access = True File "myfile2.txt". Random access = True
⇑
4.11. Method tell(). Return the current position of the read/write pointer
The tell() method returns the current position in the stream. The general form of use tell() method as follows
position = f.tell()
where
- f – file object (stream) for which the current position is determined;
- position – the position of the read/write pointer.
Example.
# Method seek() - shift the read pointer by the specified number of bytes # 1. Write the string 'abcdefghijklmnop' to the file f1 = open('myfile10.txt', 'wt') f1.write('abcdefghijklmnop') # 2. Display the current position p = f1.tell() print("p = ", p) # p = 16 # 2. close the file f1.close() # 3. Open file for reading f1 = open('myfile10.txt', 'rt') # 3.1. Print the current position p2 = f1.tell() print("p2 = ", p2) # p2 = 0 # 3.2. Shift position on the 5 characters to the end of file f1.seek(5, 0) p3 = f1.tell() # get the current position print("p3 = ", p3) # p3 = 5 f1.close()
Program result
p = 16 p2 = 0 p3 = 5
⇑
4.12. Method truncate(). Resize file
The truncate() method is used to resize a file in write mode (‘w’). If you try to resize the file in read mode, the system will throw an exception.
According to the documentation, the general form of using the method is as follows
size = f.truncate(newSize = None)
here
- f – file stream;
- newSize – the new file size that is being installed. If newSize is smaller than the current size, then the data in the file is cut from the end of the file. If newSize is larger than the current size, then the data is padded with zero values of ‘\x00’. The default value of newSize = None.
Calling truncate() without parameters (newSize = None by default) will return the current file size in bytes.
Example.
# Method truncate() - resize file (file stream) # 1. Write to file, resize file # 1.1. Write the string '01234567890' to the file - file size 10 bytes f1 = open('myfile11.txt', 'wt') f1.write('0123456789') # size 10 bytes # 1.2. Print file size - call truncate() without parameter size = f1.truncate() print('size = ', size) # size = 10 # 1.3. Reduce file by 2 bytes size2 = f1.truncate(8) print('size2 = ', size2) # size2 = 8 # 1.4. Increase file size to 15 bytes size3 = f1.truncate(15) print('size3 = ', size3) # size3 = 15 # 1.4. Close the file f1.close() # 2. Read recorded line from file # 2.1. Open the file for reading f2 = open('myfile11.txt', 'rt') # 2.2. Read a line from the file and display it s = f2.readline() # s = '01234567\x00\x00\x00\x00\x00\x00\x00' print('s=', s, '.') f2.close()
Program result
size = 10 size2 = 8 size3 = 15 s= 01234567 .
⇑
4.13. Method writable(). Determine, if file stream supports writing
The writable() method determines whether the stream supports writing. According to the documentation, the general form of using the method is as follows
fWrite = f.writable()
here
- f – file stream;
- fWrite – result. If fWrite = True, then the file stream supports writing. You can use the write() and truncate() functions. If fWrite = False, then using the write() and truncate() functions will throw an OSError exception.
Example.
# Method writable() # 1. Open the file for reading and check the result f1 = open('myfile1.bin', 'rb') # binary mode if f1.writable(): print("File object f1 supports writing.") else: print("File object f1 doesn't support writing.") f1.close() # 2. Open the file for writing and check the result f1 = open('myfile12.txt', 'wt') # Text mode if f1.writable(): # if f1 is writable f1.write('Hello world!') # write to the file print("Write to f1: 'Hello world!' - OK!") else: print("File object f1 doesn't support writing") f1.close()
Program result
File object f1 doesn't support writing. Write to f1: 'Hello world!' - OK!
⇑
4.14. Method writelines(). Writing a list of lines to a file
The writelines() method implements writing a list of strings to a stream. The general form of using the method is as follows:
f.writelines(lines)
here
- f – a file stream that is open for writing;;
- lines – list of lines to be written to the file. Lines are added as they appear in the lines list, that is, no additional delimiter characters are added. If, in the future, you need to read these lines from a file, then you need to add a separator character (for example ‘\n’ or another character) to each line in the list.
Example.
# Method writelines() - write a list of lines to a file # Case 1. The line end character is not added to the list of lines. # 1.1. Open file for writing in text mode f1 = open('myfile13.txt', 'wt') # text mode # 1.2. The names of the seasons are given - without the end of line character Seasons = [ 'Winter', 'Spring', 'Summer', 'Autumn'] # 1.3. Write an array of strings to the file without using the '\n' character f1.writelines(Seasons) # In the file: 'WinterSpringSummerAutumn' # 1.4. Close the file 'myfile13.txt' f1.close() # ---------------------------------------------------- # Case 2. A newline character is added to each line of the list. # 2.1. Open a new file for writing in text mode f2 = open('myfile14.txt', 'w') # 2.2. Define a new list of season names - with the symbol '\n' Seasons2 = [ 'Winter\n', 'Spring\n', 'Summer\n', 'Autumn\n' ] # 2.3. Write to 'myfile14.txt' f2.writelines(Seasons2) # In the file, each list item in a new line # 2.4. Close the file f2.close()
The contents of the file myfile13.txt
WinterSpringSummerAutumn
The contents of the file myfile14.txt
Winter Spring Summer Autumn
⇑
Related topics
- Files. General concepts. Opening/closing a file. Functions open(), close()
- Examples of working with text files
- Binary files. Examples of working of binary files
⇑