Handling Files in Python

Handling Files in Python

Handling Files in Python. A guide to learning about how to handle files using different libraries to perform different functions in Python.

A guide to learning about how to handle files using different libraries to perform different functions in Python.

io module

The io module implements an in-memory file-like object. This object can then be used as input to output.

>>> import io

Let’s create a sentence and then create an object file for the sentence..

>>> txt = 'Python is fun and easy'

>>> f = io.StringIO(txt)

This will create an object “f” that we can treat just like a file.

Image for post

>>> f.read()
'Python is fun and easy'

>>> f.write(' Python is nice languague')
25

Setting the cursor back to start.

>>> f.seek(0)
0

>>> f.read()
'Python is fun and easy Python is nice languague'

os module

The os module helps in interacting with the operating system. Some functions it can perform are opening and reading files programmatically. Let’s go through some of its functions.

>>> import os

To get the current directory.

>>> os.getcwd()
'D:\\JAY\\projects\\Python_guide\\Python modules and packages'

To list the directories in the current directory and any other directory.

>>> os.listdir()
['.ipynb_checkpoints',
 'Collections module in Python.ipynb',
 'Datetime module in python.ipynb',
 'Debugger module in Python.ipynb',
 'Handling files in\xa0Python.ipynb',
 'Modules and packages in python',
 'Name and main in python',
 'README.md',
 'Regular expression in Python.ipynb',
 'Timing module in Python - timeit.ipynb']
>>> os.listdir("C:\\Users")
['All Users', 'Default', 'Default User', 'desktop.ini', 'Jayashree', 'Public']

shutil module

The built-in shutil module helps to move files to different locations.

>>> import shutil

>>> shutil.move('demo.txt','D:\\demo')
'D:\\demo\\demo.txt'
>>> os.listdir('D:\\demo')
['demo.txt']
>>> shutil.move('D:\\demo\demo.txt', os.getcwd())
'D:\\JAY\\projects\\Python_guide\\Python modules and packages\\demo.txt'
>>> os.listdir()
['.ipynb_checkpoints',
 'Collections module in Python.ipynb',
 'Datetime module in python.ipynb',
 'Debugger module in Python.ipynb',
 'demo.txt',
 'Handling files in\xa0Python.ipynb',
 'Modules and packages in python',
 'Name and main in python',
 'README.md',
 'Regular expression in Python.ipynb',
 'Timing module in Python - timeit.ipynb']

send2trash module

The os module provides 3 methods for deleting files:

  • os.unlink(path) which deletes a file at the path your provide
  • os.rmdir(path) which deletes a folder (folder must be empty) at the path you provide
  • shutil.rmtree(path) this is the most dangerous, as it will remove all files and folders contained in the path.

All of these methods can not be reversed! This means if you make a mistake you won’t be able to recover the file. Instead, we will use the send2trash module. A safer alternative that sends deleted files to the trash bin instead of permanent removal.

>>> !pip install send2trash
Requirement already satisfied: send2trash in d:\anaconda3\lib\site-packages (1.5.0)

>>> import send2trash
>>> os.listdir()
['.ipynb_checkpoints',
 'Collections module in Python.ipynb',
 'Datetime module in python.ipynb',
 'Debugger module in Python.ipynb',
 'demo.txt',
 'Handling files in\xa0Python.ipynb',
 'Modules and packages in python',
 'Name and main in python',
 'README.md',
 'Regular expression in Python.ipynb',
 'Timing module in Python - timeit.ipynb']
>>> send2trash.send2trash('demo.txt')
>>> os.listdir()
['.ipynb_checkpoints',
 'Collections module in Python.ipynb',
 'Datetime module in python.ipynb',
 'Debugger module in Python.ipynb',
 'Handling files in\xa0Python.ipynb',
 'Modules and packages in python',
 'Name and main in python',
 'README.md',
 'Regular expression in Python.ipynb',
 'Timing module in Python - timeit.ipynb']

Going through a directory

The os.walk() method helps to walk through files and folders recursively.

>>> os.listdir()
['.ipynb_checkpoints',
 'Collections module in Python.ipynb',
 'Datetime module in python.ipynb',
 'Debugger module in Python.ipynb',
 'Handling files in\xa0Python.ipynb',
 'Modules and packages in python',
 'Name and main in python',
 'README.md',
 'Regular expression in Python.ipynb',
 'Timing module in Python - timeit.ipynb']
>>> for folder, sub_folder, files in os.walk('..\Python modules and packages'):
        print("Currently looking at folder: " + folder)
        print('\n')
        print("The subfolders are: ")
        for sub_fold in sub_folder:
            print("\t Subfolder: " + sub_fold)
        print('\n')
        print("The files are: ")
        for f in files:
            print("\t File: " + f)
        print('\n')
Currently looking at folder: ..\Python modules and packages
The subfolders are: 
     Subfolder: .ipynb_checkpoints
     Subfolder: Modules and packages in python
     Subfolder: Name and main in python
The files are: 
     File: Collections module in Python.ipynb
     File: Datetime module in python.ipynb
     File: Debugger module in Python.ipynb
     File: Handling files in Python.ipynb
     File: README.md
     File: Regular expression in Python.ipynb
     File: Timing module in Python - timeit.ipynb
Currently looking at folder: ..\Python modules and packages\.ipynb_checkpoints
The subfolders are: 
The files are: 
     File: Handling files in Python-checkpoint.ipynb
Currently looking at folder: ..\Python modules and packages\Modules and packages in python
The subfolders are: 
     Subfolder: MyPackage
The files are: 
     File: program.py
     File: tree.txt
Currently looking at folder: ..\Python modules and packages\Modules and packages in python\MyPackage
The subfolders are: 
     Subfolder: SubPackage
The files are: 
     File: main_script.py
     File: __init__.py
Currently looking at folder: ..\Python modules and packages\Modules and packages in python\MyPackage\SubPackage
The subfolders are: 
The files are: 
     File: sub_script.py
     File: __init__.py
Currently looking at folder: ..\Python modules and packages\Name and main in python
The subfolders are: 
The files are: 
     File: test1.py
     File: test2.py

programming python developer

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Hire Python Developers

Are you looking for experienced, reliable, and qualified Python developers? If yes, you have reached the right place. At **[HourlyDeveloper.io](https://hourlydeveloper.io/ "HourlyDeveloper.io")**, our full-stack Python development services...

Hire Python Developers India

Looking to build robust, scalable, and dynamic responsive websites and applications in Python? At **[HourlyDeveloper.io](https://hourlydeveloper.io/ "HourlyDeveloper.io")**, we constantly endeavor to give you exactly what you need. If you need to...

Python Tricks Every Developer Should Know

In this tutorial, you’re going to learn a variety of Python tricks that you can use to write your Python code in a more readable and efficient way like a pro.

Top Python Development Companies | Hire Python Developers

After analyzing clients and market requirements, TopDevelopers has come up with the list of the best Python service providers. These top-rated Python developers are widely appreciated for their professionalism in handling diverse projects. When...

Python Programming: A Beginner’s Guide

Python is an interpreted, high-level, powerful general-purpose programming language. You may ask, Python’s a snake right? and Why is this programming language named after it?