Python coding – File handling

In anything you do with computers  (python coding), you must surely work with files in one way or the other. In this post, we will be learning how to create, modify or even delete files using Python programming.

open () function

This function is essentially used in almost every operation involving files and file management in Python. The open() function is used to create a file object for reading or writing to or from files. The syntax is shown below:

open(path+filename, mode)

The path is the location of the file you want to access or manipulate, while the mode specifies the kind of operations to be performed on the file. For instance, to read an already existing file, you can use the ‘r’ or read-only mode.


x = open('data.txt', 'r')

Below are highlights of some of the available access modes for accessing or manipulating files in Python.

Access modes

r –  read only

rb – read-only in binary format.

r+ – read and write. File pointer at the beginning.

rb+ – read and write in binary. File pointer at the beginning.

w – write only. Overwrites file contents if it exists

wb – write only in binary. Overwrites file contents if it exists

w+ – read and write. Overwrites file data.

wb+ – read and write binary. Overwrites file data.

a – opens a file in the append mode. It doesn’t allow reading.

ab – opens a file in the append mode in binary format.

a+ opens a file in append mode and supports reading the file.

ab+ opens a file in append mode in binary format and supports reading the file.

Creating and Reading files in Python

Now, let’s demonstrate how to create and read files in Python in various access modes.


file = open('data.txt', 'r')

#Error if file or path doesn't exist

file = open('data.txt', 'w')

#Opens a file in write-only mode and creates the file if it does not exist

In the example below, we will be using the for loop to generate data and then write the data into a file named data.txt.


file = open('data.txt', 'w')

for number in range(10):

    file.write(f'line {number + 1}\n')

file.close()

file = open('data.txt', 'r')

print(file.read())

#outputs

# line 1

# line 2

# line 3

# line 4

# line 5

# line 6

# line 7

# line 8

# line 9

# line 10

File paths

The open() function expects an argument representing the file to be created or modified. By default, python searches for the file in the current working directory.

However, if the file in question is in a different location, you are required to provide the path, otherwise, you will get an error.

The path could be relative or absolute.


file = open('path/data.txt')

Built-in functions

These are in-built functions that allow you to perform operations on the object returned by the open function.

read()

This method returns the entire content of a file in the form of a string. It reads the entire content of a file at once and returns an object representing the content of the file.


file = open('data.txt')

print(file.read())

#outputs

# line 1

# line 2

# line 3

# line 4

# line 5

# line 6

# line 7

# line 8

# line 9

# line 10

readline()

This method returns a string of the lines in a file one at a time, until it reaches the end of the file, and then returns an empty string.


file = open('data.txt')

print(file.readline())

#line 1

print(file.readline())

#line 2

print(file.readline())

#line 3

readlines()

This method returns a list of all the lines in a file.


file = open('data.txt')

print(file.readlines())

#output

#['line 1\n', 'line 2\n', 'line 3\n', 'line 4\n', 'line 5\n', 'line 6\n', 'line 7\n', 'line 8\n', 'line 9\n', 'line 10\n']

write()

This method is used to write a given text to a file. The syntax is shown below:


file = open('data.txt', 'w')

file.write('Hello there!')

file.close()

file = open('data.txt')

print(file.read())


#output

#Hello there!

writelines()

This is used to write a string or a list into a file. In the case of lists, items in the list are treated as strings when writing to a file.


file = open('data.txt', 'w')

file.writelines('hello world')

file.close()

file = open('data.txt')

print(file.read())

#output

#'hello world'


file = open('data.txt', 'w')

data = ['line 1\n', 'line 2\n', 'line 3\n']

file.writelines(data)

file.close()

file = open('data.txt')

print(file.read())

#output

# line 1

# line 2

# line 3

seek()

Seek is used to indicate the position from where a file would be read or written to. Just like the strings, an index of 0 means the first position in the file.


file = open('data.txt', 'r')

file.seek(0)

print(file.read())

file.seek(5)

print(file.read())

#output

# hello world

#  world

tell()

Tell is used to determine the actual position where the file pointer is at.


file = open('data.txt', 'r')

print(file.tell())

print(file.read())

print(file.tell())

#output

# 0

# hello world

# 11

readable()

This specifies if a file is opened for reading or not. It returns True if the file is opened for reading and False if otherwise.


file = open('data.txt')

print(file.readable())

file = open('data.txt', 'w')

print(file.readable())

#outputs

# True

# False

writable()

This method determines whether the open file is writable or not.


file = open('data.txt')

print(file.writable())

file = open('data.txt', 'w')

print(file.writable())


#outputs

# False

# True

close

It is used to close and flush the IO object if it’s still open. If a file is not properly closed, there are chances that the file could get corrupted or lost.


file = open('data.txt')

file.close()

Apart from using the close method to close a file, you can enclose the open() function in a with statement. This way, when it is out of scope, the file is automatically closed as shown below.

with open(‘data.txt’) as file:
output = file.read()

truncate()

This is used to reduce the content of a file to the given number of characters or bytes.


file = open('data.txt', 'a')

file.truncate(1)

file.close()

file = open('data.txt')

print(file.read())


#outputs

# h

Attributes of the file methods

Name

This attribute returns the name of the file.


file = open('data.txt')

print(file.name)


#outputs

# data.txt

Closed

This determines whether the IO object is closed or not. It returns True if the IO object is closed and False if it is still open.


file = open('data.txt')

print(file.closed)



file.close()

print(file.closed)



#outputs

# False

# True

Working with binary data

Fundamentally, a computer stores data in bytes. The simplest unit of data storage in the computer is 1 byte. So, whether you are working with strings, integers, lists and so on, it’s eventually stored as bytes in a computer.

Interestingly, bytes are not human-readable. They are essentially sequences of 1s and 0s. A byte is prefixed with b in Python.


print(b'hello')

#b'100'

print(type(b'hello'))

#output

#<class 'bytes'>

In binary data, each character is represented by the byte values of the character. This is also known as the Unicode code for that particular character. You can as well use the ord() method to return that number.


data = b'hello'

for num in data:

    print(num)

#outputs

# 104

# 101

# 108

# 108

# 111

print(ord('h'))

print(ord('e'))

print(ord('l'))

print(ord('o'))


#outputs

# 104

# 101

# 108

# 111

decode() Function

To convert a byte to a string, the decode function is used.


data = b'hello'

print(data.decode())



#output

# hello

You can also use the str () function to do the same passing in the encoding format.


data = b'hello'

print(str(data, encoding='utf-8'))

#output

# hello

Bytearrays

Bytearray is a sequence of bytes.


data = b'hello'

b_data = bytearray(data)

print(b_data)

#output

# bytearray(b'hello')

Converting string to bytearray


b_data = bytearray('hello', 'utf-8')

print(b_data)

#output

# bytearray(b'hello')

You still use the decode to convert a given bytearray to a string.


data = bytearray('hello', 'utf-8').decode()

print(data)


#output

# hello

Writing binary data to file


data = b'hello'

file = open('data.txt', 'wb')

file.write(data)

file.close()

file = open('data.txt', 'rb')

output = file.read()

print(output)

#output

# b'hello'

Copy Files

You can easily copy files from one location to another on the computer using the copy method in the shutil module in Python.


import shutil

src = 'data.txt'

destination = 'destination/data.txt'

shutil.copy(src, destination)

#'destination/data.txt'

Renaming files

You can rename a file in Python using os.rename() method in the os module. You’re required to provide the path of the file to be renamed and the new name.


import os

os.rename('destination/data.txt', 'renamed.txt')

Deleting Files

You can rename a file in Python using the os.remove() method

import os

os.remove('data.txt')

 

Leave a Reply

Your email address will not be published. Required fields are marked *