in , ,

Python File I/O

Python File I/O

In this tutorial, you’ll find out about the Python file operations. All the more explicitly, opening a file, perusing from it, writing into it, closing it, and different file methods that you ought to know about.

File

Files are named locations on disk to store related information. They are utilized to for all time store information in a non-unpredictable memory (for example hard disk).

Since Random Access Memory (RAM) is volatile (which loses its data when the computer is turned off), we use files for future use of the data by permanently storing them.

When we need to peruse from or keep in touch with a record, we have to open it first. At the point when we are done, it should be shut so the assets that are attached to the document are liberated.

Hence, in Python, a file operation takes place in the following order:

Open a file
Read or write (perform the operation)
Close the file


Opening Files in Python

Python has a built-in open() function to open a file. This function returns a file object, also called a handle, as it is used to read or modify the file accordingly.

>>> f = open("test.txt")    # open file in current directory
>>> f = open("C:/Python38/README.txt")  # specifying full path

We can determine the mode while opening a file. In mode, we determine whether we want to read r, write w, or append a to the file. We can also determine on the off chance that we need to open the record in text mode or parallel mode.

The default is perusing in text mode. In this mode, we get strings when perusing from the record.

Then again, the twofold mode returns bytes and this is the mode to be utilized when managing non-text records like pictures or executable files.

ModeDescription
rOpens a file for reading. (default)
wOpens a file for writing. Creates a new file if it does not exist or truncates the file if it exists.
xOpens a file for exclusive creation. If the file already exists, the operation fails.
aOpens a file for appending at the end of the file without truncating it. Creates a new file if it does not exist.
tOpens in text mode. (default)
bOpens in binary mode.
+Opens a file for updating (reading and writing)
f = open("test.txt")      # equivalent to 'r' or 'rt'
f = open("test.txt",'w')  # write in text mode
f = open("img.bmp",'r+b') # read and write in binary mode

unlike other languages, the character a doesn’t suggest the number 97 until it is encoded using ASCII (or other equal encodings).

Besides, the default encoding is stage subordinate. In windows, it is cp1252 yet utf-8 in Linux.

So, we must not also rely on the default encoding or, in all likelihood, our code will carry on distinctively in various stages.

Thus, when working with documents in text mode, it is enthusiastically prescribed to indicate the encoding type.

f = open("test.txt", mode='r', encoding='utf-8')

Closing Files in Python

When we are done with performing operations on the file, we need to properly close the file.

Closing a file will free up the resources that were tied with the file. It is done using the close() method available in Python.

Python has a garbage collector to clean up unreferenced objects but we must not rely on it to close the file.

f = open("test.txt", encoding = 'utf-8')
# perform file operations
f.close()

This method is not entirely safe. If an exception occurs when we are performing some operation with the file, the code exits without closing the file.

A safer way is to use a try…finally block.

try:
   f = open("test.txt", encoding = 'utf-8')
   # perform file operations
finally:
   f.close()

This way, we are guaranteeing that the record is appropriately shut regardless of whether a special case is raised that causes the program stream to stop.

The best way to close a file is by using the explanation. This ensures that the file is closed when the square inside the with statement is exited.

We don’t need to explicitly call the close() method. It is done internally.

with open("test.txt", encoding = 'utf-8') as f:
   # perform file operations

Writing to Files in Python

So as to compose into a document in Python, we have to open it in write w, append a or exclusive creation x mode.

We need to be careful with the w mode, as it will overwrite into the document on the off chance that it as of now exists. Because of this, all the past information is eradicated.

Writing a string or grouping of bytes (for twofold documents) is finished using the write() method. This strategy restores the number of characters kept in touch with the file.

with open("test.txt",'w',encoding = 'utf-8') as f:
   f.write("my first file\n")
   f.write("This file\n\n")
   f.write("contains three lines\n")

This program will make a new file named test.txt in the current catalog on the off chance that it doesn’t exist. On the off chance that it exists, it is overwritten.

We should incorporate the newline characters ourselves to recognize the various lines.


Reading Files in Python

To read a file in Python, we should open the document in perusing r mode.

There are different methods available for this purpose. We can use the read(size) technique to peruse in the size number of the data. If the size boundary isn’t indicated, it peruses and returns up to the furthest limit of the file.

We can peruse the text.txt file we wrote in the above section in the following way:

>>> f = open("test.txt",'r',encoding = 'utf-8')
>>> f.read(4)    # read the first 4 data
'This'

>>> f.read(4)    # read the next 4 data
' is '

>>> f.read()     # read in the rest till end of file
'my first file\nThis file\ncontains three lines\n'

>>> f.read()  # further reading returns empty sting
''

We can see that the read() method returns a newline as ‘\n’. Once the end of the file is reached, we get an empty string on further reading.

We can change our current file cursor (position) using the seek() method. Similarly, the tell() method returns our current position (in the number of bytes).

>>> f.tell()    # get the current file position
56

>>> f.seek(0)   # bring file cursor to initial position
0

>>> print(f.read())  # read the entire file
This is my first file
This file
contains three lines

We can read a file line-by-line using a for loop. This is both efficient and fast.

>>> for line in f:
...     print(line, end = '')
...
This is my first file
This file
contains three lines

In this program, the lines in the file itself include a newline character \n. So, we use the end parameter of the print() function to avoid two newlines when printing.

Alternatively, we can use the readline() method to read individual lines of a file. This method reads a file until the new line, including the newline character.

>>> f.readline()
'This is my first file\n'

>>> f.readline()
'This file\n'

>>> f.readline()
'contains three lines\n'

>>> f.readline()
''

Lastly, the readlines() method returns a list of remaining lines of the entire file. All these reading methods return empty values when the end of file (EOF) is reached.

>>> f.readlines()
['This is my first file\n', 'This file\n', 'contains three lines\n']

Python File Methods

There are different techniques accessible with the document object. Some of them have been utilized in the above models.

Here is the finished rundown of techniques in text mode with a short depiction:

MethodDescription
close()Closes an open file. It has no effect if the file is already closed.
detach()Separates the underlying binary buffer from the TextIOBase and return it.
fileno()Returns an integer number (file descriptor) of the file.
flush()Flushes the write buffer of the file stream.
isatty()Returns True if the file stream is interactive.
read(n)Reads at most n characters from the file. Reads till the end of the file if it is negative or None.
readable()Returns True if the file stream can be read from.
readline(n=-1)Reads and returns one line from the file. Reads in at most n bytes if specified.
readlines(n=-1)Reads and returns a list of lines from the file. Reads in at most n bytes/characters if specified.
seek(offset,from=SEEK_SET)Changes the file position to offset bytes, in reference to from (start, current, end).
seekable()Returns True if the file stream supports random access.
tell()Returns the current file location.
truncate(size=None)Resizes the file stream to size bytes. If the size is not specified, resizes to the current location.
writable()Returns True if the file stream can be written to.
write(s)Writes the string s to the file and returns the number of characters written.
writelines(lines)Writes a list of lines to the file.

Please feel free to give your comment if you face any difficulty here.

For more Articles click on the below link.

salman khan

Written by worldofitech

Leave a Reply

Python Dictionary

Python Dictionary

Python Directory and Files Management

Python Directory and Files Management