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:
- text I/O
- binary I/O
- 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
strobject to the
write()method of a binary stream will raise a
TypeError. So will giving a
bytesobject to the
write()method of a text stream.
- Changed in version 3.3: Operations that used to raise
IOErroris now an alias of
See I/O in some breaf:
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")
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
'b' in the mode string:
f = open("myfile.jpg", "rb")
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)
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.
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)
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.
- '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.
- '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.
- 'a' – Append Mode : This mode adds information to the end of the file automatically. File pointer is placed at the end of the file.
- '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.
- '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.
- '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
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:
- 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
withkeyword. This keyword closes the file automatically after the nested code block completes.
There are a few functions for reading from a file. let's discuss them one by one with usecases.
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).
with open("workData.txt", "r+") as work_data: print("This is the file name: ", work_data.name) line = work_data.read() print(line)
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.
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)
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)
For writing in a file, python has a built-in function
when we open the file as
w mode so that clear out all existing data so opening the file in
append mode is preferable.
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")
Thank you for reading