#27 - Python File I/O

#27 - Python File I/O

By Ifeanyi Omeata


Topics:


1. File I/O


1. File I/O


>>Return to Menu





Files
Files are named locations on disk to store related information.
They are used to permanently store data in a non-volatile memory (e.g. hard disk).
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
Mode    Description
r    = Opens a file for reading. (default)
w    = Opens a file for writing. Creates a new file if it does not exist or truncates the file if it exists.
x    = Opens a file for exclusive creation. If the file already exists, the operation fails.
a    = Opens a file for appending at the end of the file without truncating it. Creates a new file if it does not exist.
t    = Opens in text mode. (default)
b    = Opens 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
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.

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

Writing to Files in Python
In order to write into a file in Python, we need 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 file if it already exists. Due to this, all the previous data are erased.

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")

Reading Files in Python
To read a file in Python, we must open the file in reading r mode. There are various methods available for this purpose. We can use the read(size) method to read in the size number of data. If the size parameter is not specified, it reads and returns up to the end of the file.

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 change our current file cursor (position) using the seek() method. Similarly, the tell() method returns our current position (in 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

Alternatively, we can use the readline() method to read individual lines of a file. This method reads a file till the newline, 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()

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']
Method    Description
close()     = Closes an opened file. It has no effect if the file is already closed.
detach()    = Separates the underlying binary buffer from the TextIOBase and returns 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 end of 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 an integer that represents the current position of the file's object.
truncate(size=None)    Resizes the file stream to size bytes. If size is not specified, resizes to 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.

Example:

from translate import Translator

translator= Translator(to_lang="fr")
try:
    with open('./text.txt', mode='r') as my_file:
        message = my_file.read()
        translation = translator.translate(message)
        print(translation)
        with open('./translation.txt', mode='w') as t_file:
            t_file.write(translation)
except FileNotFoundError as err:
    print('file does not exist')
    raise err from err

with open('person.txt') as my_file:
    print(my_file.read())

with open('person.txt', mode='r') as my_file:
    print(my_file.read())

with open('someone.txt', mode='w') as my_file:
    message = my_file.write('Somebody has arrived!')
    print(message)

with open('someone.txt', mode='a') as my_file:
    message = my_file.write(' Hello Everybody!')
    print(message)

with open('./app/someone.txt', mode='r') as my_file:
    message = my_file.read()
    print(message)

try:
    with open('someone.txt', mode='r') as my_file:
        message = my_file.read()
        print(message)
except FileNotFoundError as err:
    print('file does not exist')
    raise err from err

my_file = open('person.txt')
print(my_file.read())
my_file.close()    

with open('person.txt') as my_file:
    print(my_file.read())
    my_file.seek(0)
    print(my_file.read())

with open('person.txt') as my_file:
    print(my_file.readline())
    print(my_file.readline())
    print(my_file.readline())

with open('person.txt') as my_file:
    my_file = open('person.txt')
    print(my_file.readlines())

#End


Hope you enjoyed this! :) Follow me for more contents...


Get in Touch:
ifeanyiomeata.com

Youtube: youtube.com/c/IfeanyiOmeata
Linkedin: linkedin.com/in/omeatai
Twitter: twitter.com/iomeata
Github: github.com/omeatai
Stackoverflow: stackoverflow.com/users/2689166/omeatai
Hashnode: hashnode.com/@omeatai
Medium: medium.com/@omeatai
© 2022