DEV Community

Cover image for Python: File I/O
Aman Gupta
Aman Gupta

Posted on

Python: File I/O

So today here we discuss how we can work with files in python and how taking I/O in python.So lets first we talk about I/O streams in python. In python there are basically three main I/O:

  1. text I/O
  2. binary I/O
  3. raw I/O A concrete object belonging to any of these categories is called a file object.Independent of its category, each concrete stream object will also have various capabilities: it can be read-only, write-only, or read-write. It can also allow arbitrary random access (seeking forwards or backwards to any location), or only sequential access (for example in the case of a socket or pipe).
  • All streams are careful about the type of data you give to them. For example giving a str object to the write() method of a binary stream will raise a TypeError. So will giving a bytes object to the write() method of a text stream.
  • Changed in version 3.3: Operations that used to raise IOError now raise OSError, since IOError is now an alias of OSError.

See I/O in some breaf:

1. text I/O

Text I/O expects and produces str objects. This means that whenever the backing store is natively made of bytes, encoding and decoding of data is made transparently as well as optional translation of platform-specific newline characters.

The easiest way to create a text stream is with open(), optionally specifying an encoding:

f = open("myfile.txt", "r", encoding="utf-8")
Enter fullscreen mode Exit fullscreen mode

2. binary I/O

Binary I/O expects bytes-like objects and produces bytes objects. No encoding, decoding, or newline translation is performed. This category of streams can be used for all kinds of non-text data, and also when manual control over the handling of text data is desired.
The easiest way to create a binary stream is with open() with 'b' in the mode string:

f = open("myfile.jpg", "rb")
Enter fullscreen mode Exit fullscreen mode

3. raw I/O

Raw I/O is generally used as a low-level building-block for binary and text streams; it is rarely useful to directly manipulate a raw stream from user code. Nevertheless, we can create a raw stream by opening a file in binary mode with buffering disabled.

f = open("myfile.jpg", "rb", buffering=0)
Enter fullscreen mode Exit fullscreen mode

So we discuss streams in python. So how we can read and write files in python?
In python, we didn't worry about importing any library for handling files. Python has file handling tools built-in part of its core module. Python has a built-in set of functions that handle everything you need to read and write to files. We’ll now take a closer look at them.

Opening File in Python

for opening file in python, there is a built-in method open() which return object called data_file.The basic function usage for open() is the following:

file_object = open(filename, mode)
Enter fullscreen mode Exit fullscreen mode

In above syntax filename is the name of the file that you want to interact with, and mode in the open function tells Python what we want to do with the file. There are multiple modes that you can specify when dealing with text files.

  1. 'w' - Write Mode : This mode is used when the file needs to be altered and information changed or added. Keep in mind that this erases the existing file to create a new one. File pointer is placed at the beginning of the file.
  2. 'r' - Read Mode : This mode is used when the information in the file is only meant to be read and not changed in any way. File pointer is placed at the beginning of the file.
  3. 'a' – Append Mode : This mode adds information to the end of the file automatically. File pointer is placed at the end of the file.
  4. 'r+' – Read/Write Mode : This is used when you will be making changes to the file and reading information from it. The file pointer is placed at the beginning of the file.
  5. 'a+' – Append and Read Mode : A file is opened to allow data to be added to the end of the file and lets your program read information as well. File pointer is placed at the end of the file.
  6. 'x' – Exclusive Creation Mode : This mode is used exclusively to create a file. If a file of the same name already exists, the function call will fail.

When we are using binary files, we will use the same mode specifiers. However, we add a b to the end. So a write mode specifier for a binary file is 'wb'. The others are 'rb', 'ab', 'r+b', and 'a+b' respectively.

File Closing in python

The closing file is most important when we working with files in python. It frees up system resources that program is using for I/O purposes. When writing a program that has space or memory constraints, this lets us manage resources effectively.

Also, closing a file ensures that any pending data is written out to the underlying storage system, for example, our local disk drive. By explicitly closing the file you ensure that any buffered data held in memory is flushed out and written to the file.

The function to close a file in Python is simply fileobject.close(). Using the data_file file object that we created in the previous example, the command to close it would be:

file_object.close()
Enter fullscreen mode Exit fullscreen mode
  • After you close a file, you can’t access it any longer until you reopen it at a later date.
  • In Python, the best practice for opening and closing files uses the with keyword. This keyword closes the file automatically after the nested code block completes.

Reading from file

There are a few functions for reading from a file. let's discuss them one by one with usecases.

1. read(size)

By using this method we read a specific no of bytes from a file. By default this method will read the entire file and print it out to the console as either a string (in text mode) or as byte objects (in binary mode).
Example :

with open("workData.txt", "r+") as work_data:
    print("This is the file name: ", work_data.name)
    line = work_data.read()
    print(line)
Enter fullscreen mode Exit fullscreen mode

2. readline(size)

By using this method we process the file line by line. size parameter here represent no of bytes from each line. by default it prints the first line of the file.
Example :

with open("workData.txt", "r+") as work_data:
     print("This is the file name: ", work_data.name)
     line_data = work_data.readline()
     print(line_data)
Enter fullscreen mode Exit fullscreen mode

3. Processing an Entire Text File Line-By-Line

The easiest way to process an entire text file line-by-line in Python is by using a simple loop:

with open("workData.txt", "r+") as work_data:
    for line in work_data:
        print(line)
Enter fullscreen mode Exit fullscreen mode

Writing in a python File

For writing in a file, python has a built-in function write().
when we open the file as w mode so that clear out all existing data so opening the file in append mode is preferable.

Example :

values = [1234, 5678, 9012]

with open("workData.txt", "a+") as work_data:
    for value in values:
        str_value = str(value)
        work_data.write(str_value)
        work_data.write("\n")
Enter fullscreen mode Exit fullscreen mode

Thank you for reading

Top comments (0)