BongoBinary

Python working with files

By Aloyce Bahati10 months, 3 weeks ago12 minutes read

python-working-with-files

 

Working with files in Python

Python working with files, Python language has a lot of tools for working with files which supports:- reading files , writing files , updating and deleting files.  Though there are multiple module for performing this task. In most cases you will be using the tools from python standard library.

 

Opening files:

Before writing or reading files in python , you have to first open it. To open a file in python you utilize the open() function. The open() function takes take a string argument which is a path to the file to open. If the file is on different directory then you have to specify the full path, but if the file is on the same directory as the script then you only have to write its name as shown bellow.

myFile = open("file.txt")

 

Modes for opening files:

Its crucial to know that when opening files in python you can pass the second argument to the open() function. The second argument is the mode for working with file, if mode is not provided then the default value for the mode is read (r).

 

File modes ( Text files ) :

r  – read mode (Open file for reading content only)

w – write mode ( overwrite the files if the content already exists on file / write file if no content exists/ create file if not exists)

a – append mode (open file for appending content)

t – text mode, default.

+ –  open file for updating (read and write)

x – create a new file and open it for writing

 

File modes ( Binary files / Non text files ) :

rb – read binary mode

wb – write binary mode

ab – append binary mode

(+)   can be used to give more access to the files and can be used on most modes mentioned above.

 

As:-

r+   – mode for both read and write. File pointer is at the start of the file.

w+  –  mode for both reading and writing file content. Content is replaced if file not empty.

a+  – mode for both writing and appending content.

rb+ –  mode for both read and write. File pointer is at the start of the file.

wb+ – mode for both reading and writing file content. Content is replaced if file not empty.

ab+ – mode for both writing and appending content.

 

Reading files:

Python read()  method of file object is used to read the content of the file.

It takes one parameters which is number of bytes to read. When this parameter is not provided the default value is -1 which means read the whole contents. It should be clear that the read method will return the number of bytes from the files.

 

Examples:

file = open("file.txt","r")
sixteen_characters_only = file.read(16)
whole_remaining_content = file.read()
file.close() # always remember to close the file after read operation

 

Remember: If you use read method without passing any argument all content of the file are returned (bytes). Further calling of read method will return no content (empty string).

Calling read function with number of bytes to read will return the content from the file of that size. Repeating calling read with number of bytes will return content until all content are readout.

 

File readlines method.

The readline() method of a file is used to read all the content from the files. Readline method will return all lines from the file as a list. Any attempt to call readlines after first read will return empty results.

 

Example:

>>> file = open("file.txt","r")

>>> file.readlines()

['Hello world \n', 'this is line 2\n', 'this is line 3 \n', 'and this is line 4\n', '\n']

>>> file.readlines()

[]

>>> file.close()

readline() method is not the only way of reading all lines from a file. You can also use the forloop to access each line from the file.

Example:

>>> for line in open("file.txt"):
... print(line)

...

Hello world

this is line 2

this is line 3

and this is line 4

>>>

 

Writing files with python.

We have seen previously that we can easily read the content of the file using file read() method. In order to write the file with python language you have to do the following.

1. Make sure file is opened on write / append mode

2. use file write method.

 

File write method write()

The write method take argument (String) which is the content to written to the file, and returns number of bytes which have been written to the file (int).

If the mode set is “w”. The previous content of the file will be overwritten.

 

>>> file = open("file.txt", "w")
>>> file.write("Hi there")
8

 

Reading the written content:-

>>> file = open("file.txt", "r")
>>> content = file.read()
>>> print(content)
Hi there
>>> file.close()
>>>

 

Note: The file write() method will overwrite the content of the file. If you want to preserve the previous you may use different approach and we shall see that on the coming sections.

If you open the file on the write mode and immediately close it the content will also be deleted regardless of whether you wrote something or not.

If you use “w” as a mode you can only write, If the file does not exists new file will be created. You can not read at the same time. To read and write at the same time you may use “w+”.

file close() method.

 

To avoid wasting resources , you should always remember to close file once you are done working with them. On the example bellow we will see other way of handling file open and close using with statement.

>>> with open("file.txt") as file:
... content = file.read()
... print(content)
...
New content
>>>

The code snippet handle file opening and close automatic. The file is automatically closed at the end of with statement.

 

Though the with is more recommended way of dealing with resources like files, you can also use try except block while dealing with files to handle closing yourself and to monitor exceptions which could rise. Note: try except block can be as well used with with statement

file = None
try:
    file = open("file.txt")
    content = file.read()
finally:
    file.close()

 

we have placed the close() method at the finally block to ensure that the file is always closed regardless of whether exception occurred or not.

 

Using os module to work with files and folders

Python deleting files.

To delete file using python language we have to use the os module. After importing the os module you can use its remove() method to delete the file.After calling remove() methods with the file name as an argument, the file will be deleted. Attempt to re-open the deleted file will fire-up FileNotFoundError.

 

>>> import os
>>> os.remove("file.txt")
>>> file = open("file.txt")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'file.txt'
>>>

 

Os module: Checking if file exists.

After deleting a file, attempt to re-open the file will result to FileNotFoundError. To avoid this exception you are advised to check if the file is availlable by using the os.path.exists() method, This method.

>>> import os
>>> os.path.exists("file.txt")
False
>>>

 

Os module: Create folder ( directory)

Os module: Deleting folder in python.

To delete folder is relative simple in python while using the os module. The os module has a rmdir() method which can help us deleting the folder using python.
 

>>> import os
>>> os.rmdir("one")
>>>

The code snippet above will delete the folder named “one”.

 

Os module: list content of the directory:

os module scandir() method can be used to show the content of any directory using python. The scandir() can be called with an argument which will be the folder to scan name. In no parameter is passed the scandir() will use the the current location of the python script.

>>> import os
>>> entries = os.scandir()
>>> entries
<posix.ScandirIterator object at 0x7faa4f9bb5e0>
>>> for ent in entries:
... print(ent)
...
<DirEntry 'file.txt'>
<DirEntry 'one'>
>>>

 

Conclussion:

Its important to know how to work with files in python. Having a good knowledge on them will save you in a long run. Please dont forget to like subscribe and follow @bongobinary social account on twiter, facebook, instagram and youtube.

 

Related articles:

Python exception handling    Python exception handling
What is new in python 3.8    Whats new in python