GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Home
  • About this blog

This view

  • Original page
  • New address

GeezerVison is showing blog.feabhas.com — Python 3 File Paths - Sticky Bits - Powered by Feabhas

← Brace initialization of user-defined types
Using a Raspberry Pi as a remote headless J-Link Server →

Python 3 File Paths

Posted on May 2, 2019 by Martin Bond

If you’ve used Python for a while you will probably be familiar with the os module for working with files and directories; often called pathnames by Linux users. In moving to Python 3 you may continue to use the same os and os.path functions from Python 2.7, however a new pathlib module provides an alternative object-oriented (OO) approach.

In this posting, we examine the common file handling situations; comparing the OO approach of pathlib against the procedural approach of os functions.

Contents

Toggle

Current Directory

To obtain the current working directory with os functions we use getcwd():

import os
cwd = os.getcwd()
print(cwd)

The cwd variable is a standard Python string object containing the directory path:

/home/feabhas

On Windows this would be, for example:

C:\Users\Feabhas

In contrast, the OO approach provided by pathlib is to create a Path object with no arguments:

from pathlib import Path
cwd = Path()
print(cwd)

Path objects encapsulate the concept of a path (the name of a file or directory on disk) but do not necessarily imply that the path exists. A Path object can be queried and used to manipulate pathnames. Converting a Path to a string for printing returns the simplest form of the path which for the current directory is always:

.

To get the full, or absolute, pathname use:

print(cwd.absolute())

which will display the same string value as returned by os.getcwd().

Directory Listing

The names in the current directory are returned by os.listdir() as a list of strings:

names = os.listdir()

Normally you’d want to examine these files. In this example, we’ll simply get the file size and modification date. To start with we need to convert each name into a pathname using os.path.join():

for name in os.listdir(cwd):
    path = os.path.join(cwd, name)

We can now use this path variable to access the file on disk. If you’ve read the wrong tutorial you may, in the past, have written:

path = cwd + '/' + name

Which works but isn’t very Pythonic If you’re a Windows user and write:

path = cwd + '\\' + name

then you have missed the part that says Python treats both forward and backward slash characters as directory separators on both Linux and Windows. In other words, it doesn’t matter which form of slash character you use – it’s all the same to Python. Of course, you may have got around the forward/backward slash issue by using the host separator character from the os module:

path = cwd + os.sep + name

None of these concatenation solutions is as clean or maintainable as the os.path.join() function.

Returning to the directory listing example code, we can read the file size and modification timestamp using two separate os.path function calls, e.g.:

import os
From datetime import datetime
for name in os.listdir(cwd):
    path = os.path.join(cwd, name)
    size = os.path.getsize(path)
    mtime = datetime.fromtimestamp(os.path.getmtime(path))
    print(f'{name} {size} bytes, modified {mtime}')

For the pathlib.Path code example we can use iterdir() which is an iterator function, which also fits nicely with our for loop approach. As the iterator yields up Path objects there is no need to join the file name with the parent directory:

for path in cwd.iterdir():

Accessing file information from a Path object is a single method call. This returns all statistics in a single object which is likely to be more efficient than the multiple os.path function calls:

stats = path.stat()

The revised OO code looks thus:

from pathlib import Path
for path in cwd.iterdir():
    stats = path.stat()
    size = stats.st_size
    mtime = datetime.fromtimestamp(stats.st_mtime)
    print(f'{path} {size} bytes, modified {mtime}')

Building Pathnames

We’ve already looked at how os.path.join() is used to build filenames. With Path objects there is a similar joinpath() method used to access files from a directory path.

Consider where we want to access a file called ‘example.settings’ in a ‘conf’ sub-directory. Using os.path.join() we would write:

settings = os.path.join(cwd, 'conf', 'example.settings')

Using a Path object we now write:

settings = cwd.joinpath('conf').joinpath('example.settings')

Alternatively, we could use the / operator on a Path object and a string (or anther Path object):

settings = cwd / 'config' / 'example.settings'

Path objects also support wildcard filename expansion, e.g.:

py_files = list(cwd.glob('*.py'))

The glob() method returns an iterator; which in this case we’ve used to initialise a list containing Path objects.

The traditional approach for expanding wildcards is to use the glob module to get back a list of strings:

import glob
py_files = glob.glob('*.py')

Both versions of the glob() method/function also support recursive wildcards using ‘**’ (but the glob.glob() method requires a recursive=True argument to enable this feature):

py_files = list(cwd.glob('**/*.py'))
py_files = glob.glob('**/*.py', recursive=True)

This capability means that you no longer need to use the cumbersome os.walk() method if all you want to do is find files that match a wildcard pattern.

Manipulating Files

The os module has many functions for manipulating files. The following example checks for a file called example.log in the current directory and then deletes it.

Using the os module:
logfile = './example.log'
if os.path.exists(logfile):
    os.remove(logfile)

The same solution using the pathlib module

logfile = Path('./example.log')
if logfile.exists():
    logfile.unlink()

Directories can be created using the os.mkdir() function or Path.mkdir() method and empty directories removed with the rmdir() function or method.

Opening Files

Finally, Python 3.6 upgraded the os and os.path functions as well as file open() to work with both strings and Path objects: this is formalised as a Path Like Object.

The procedural approach for opening all Python files in the current directory looks like:

for path in glob.iglob('*.py'):
    with open(path) as fp:
        pass

The object oriented approach looks like:

for path in Path().glob('*.py'):
    with open(path) as fp:
        pass

The Path class has a lot more capabilities in addition to those shown here. It is a more or less complete replacement for all of the os, os.path and glob functions and is described in the Python 3 pathlib documentation.

Summary

If you like OO languages such as C++ or Java you’ll probably prefer the Python 3 object-oriented approach using Path object. Whereas if you’re used to the procedural approach of C you may be be more comfortable using the os, os.path and glob functions.

As long as you’re aware that both approaches are available with Python 3 you can make an informed decision over which one to use, rather than continue to use the procedural approach without being aware that there is an alternative.

  • About
  • Latest Posts
Martin Bond
Martin Bond
Associate Instructor at Feabhas Ltd
An independent IT trainer Martin has over 40 years academic and commercial experience in open systems software engineering. He has worked with a range of technologies from real time process controllers, through compilers, to large scale parallel processing systems; and across multiple sectors including industrial systems, semi-conductor manufacturing, telecomms, banking, MoD, and government.
Martin Bond
Latest posts by Martin Bond (see all)
  • CMake Presets - August 1, 2023
  • C++20 Coroutine Iterators - September 23, 2021
  • C++20 Coroutines - September 16, 2021
Like (7)
Dislike (0)
Martin Bond
+ postsBio

An independent IT trainer Martin has over 40 years academic and commercial experience in open systems software engineering. He has worked with a range of technologies from real time process controllers, through compilers, to large scale parallel processing systems; and across multiple sectors including industrial systems, semi-conductor manufacturing, telecomms, banking, MoD, and government.

  • Martin Bond
    CMake Presets
  • Martin Bond
    C++20 Coroutine Iterators
  • Martin Bond
    C++20 Coroutines
  • Martin Bond
    CMake Part 4 – Windows 10 Host
  • Martin Bond
    CMake Part 3 – Source File Organisation
  • Martin Bond
    CMake Part 2 – Release and Debug builds
  • Martin Bond
    CMake Part 1 – The Dark Arts
  • Martin Bond
    Why We Need Build Systems
  • Martin Bond
    Python 3 Unicode and Byte Strings
  • Martin Bond
    Python 3 Type Hints

About Martin Bond

An independent IT trainer Martin has over 40 years academic and commercial experience in open systems software engineering. He has worked with a range of technologies from real time process controllers, through compilers, to large scale parallel processing systems; and across multiple sectors including industrial systems, semi-conductor manufacturing, telecomms, banking, MoD, and government.
View all posts by Martin Bond →
This entry was posted in Python, Python3. Bookmark the permalink.
← Brace initialization of user-defined types
Using a Raspberry Pi as a remote headless J-Link Server →

Leave a Reply

  • Follow Us

  • Categories

    • Agile
    • ARM
    • Build-systems
    • C/C++ Programming
    • CMSIS
    • Cortex
    • Design Issues
    • General
    • Industry Analysis
    • Linux
    • Python
    • Python3
    • RTOS
    • Security
    • Testing
    • Toolchain
    • training
    • UML
    • Uncategorized
    • webinar
  • Archives

    • February 2024
    • January 2024
    • August 2023
    • December 2022
    • November 2022
    • October 2022
    • February 2022
    • October 2021
    • September 2021
    • August 2021
    • July 2021
    • June 2021
    • May 2021
    • January 2021
    • November 2020
    • October 2020
    • August 2020
    • April 2020
    • February 2020
    • January 2020
    • October 2019
    • September 2019
    • July 2019
    • May 2019
    • April 2019
    • March 2019
    • February 2019
    • January 2019
    • December 2018
    • October 2018
    • September 2018
    • August 2018
    • July 2018
    • April 2018
    • February 2018
    • January 2018
    • December 2017
    • November 2017
    • October 2017
    • September 2017
    • August 2017
    • July 2017
    • June 2017
    • May 2017
    • April 2017
    • March 2017
    • February 2017
    • January 2017
    • December 2016
    • November 2016
    • October 2016
    • September 2016
    • August 2016
    • July 2016
    • April 2016
    • January 2016
    • December 2015
    • November 2015
    • October 2015
    • September 2015
    • August 2015
    • July 2015
    • June 2015
    • May 2015
    • January 2015
    • December 2014
    • November 2014
    • October 2014
    • September 2014
    • August 2014
    • July 2014
    • June 2014
    • May 2014
    • April 2014
    • March 2014
    • February 2014
    • January 2014
    • November 2013
    • September 2013
    • August 2013
    • July 2013
    • June 2013
    • May 2013
    • April 2013
    • February 2013
    • January 2013
    • November 2012
    • October 2012
    • August 2012
    • July 2012
    • June 2012
    • May 2012
    • April 2012
    • March 2012
    • December 2011
    • November 2011
    • June 2011
    • May 2011
    • April 2011
    • March 2011
    • February 2011
    • January 2011
    • December 2010
    • November 2010
    • October 2010
    • September 2010
    • August 2010
    • July 2010
    • June 2010
    • May 2010
    • April 2010
    • March 2010
    • February 2010
    • January 2010
    • December 2009
    • November 2009
    • October 2009
    • September 2009
  • RSS

    • RSS – Posts
  • Categories

    • Agile (15)
    • ARM (36)
    • Build-systems (8)
    • C/C++ Programming (126)
    • CMSIS (17)
    • Cortex (31)
    • Design Issues (50)
    • General (46)
    • Industry Analysis (7)
    • Linux (7)
    • Python (3)
    • Python3 (3)
    • RTOS (9)
    • Security (1)
    • Testing (24)
    • Toolchain (8)
    • training (14)
    • UML (10)
    • Uncategorized (1)
    • webinar (1)
  • Tags

    • Analysis
    • ARM
    • Baker's Dozen
    • C++
    • C++0x
    • C++1y
    • C++2a
    • C++11
    • C++14
    • C++20
    • C Declarations
    • C Definitions
    • Class
    • CM
    • CMSIS
    • Configuration Management
    • constructor
    • copy policy
    • C Programming
    • design
    • docker
    • functions
    • GPIO
    • hardware manipulation
    • inheritance
    • interface
    • IO
    • linux
    • Modern C++
    • Modern C++. C++11. C++14
    • move policy
    • move semantics
    • Mutex
    • Overloading
    • Polymorphism
    • quality
    • Requirements
    • Revision Control
    • RTOS
    • Templates
    • Testing
    • training
    • UML
    • Use Case
    • Use Cases
  • Archives

    • February 2024 (1)
    • January 2024 (1)
    • August 2023 (1)
    • December 2022 (1)
    • November 2022 (1)
    • October 2022 (1)
    • February 2022 (1)
    • October 2021 (1)
    • September 2021 (3)
    • August 2021 (2)
    • July 2021 (2)
    • June 2021 (1)
    • May 2021 (1)
    • January 2021 (2)
    • November 2020 (1)
    • October 2020 (2)
    • August 2020 (1)
    • April 2020 (1)
    • February 2020 (3)
    • January 2020 (1)
    • October 2019 (1)
    • September 2019 (2)
    • July 2019 (1)
    • May 2019 (1)
    • April 2019 (1)
    • March 2019 (1)
    • February 2019 (2)
    • January 2019 (1)
    • December 2018 (2)
    • October 2018 (2)
    • September 2018 (1)
    • August 2018 (1)
    • July 2018 (1)
    • April 2018 (2)
    • February 2018 (1)
    • January 2018 (1)
    • December 2017 (2)
    • November 2017 (1)
    • October 2017 (1)
    • September 2017 (1)
    • August 2017 (1)
    • July 2017 (2)
    • June 2017 (1)
    • May 2017 (2)
    • April 2017 (2)
    • March 2017 (2)
    • February 2017 (2)
    • January 2017 (1)
    • December 2016 (2)
    • November 2016 (1)
    • October 2016 (2)
    • September 2016 (1)
    • August 2016 (1)
    • July 2016 (2)
    • April 2016 (1)
    • January 2016 (1)
    • December 2015 (2)
    • November 2015 (1)
    • October 2015 (2)
    • September 2015 (3)
    • August 2015 (2)
    • July 2015 (3)
    • June 2015 (2)
    • May 2015 (3)
    • January 2015 (2)
    • December 2014 (2)
    • November 2014 (2)
    • October 2014 (1)
    • September 2014 (2)
    • August 2014 (2)
    • July 2014 (2)
    • June 2014 (2)
    • May 2014 (1)
    • April 2014 (1)
    • March 2014 (2)
    • February 2014 (1)
    • January 2014 (2)
    • November 2013 (1)
    • September 2013 (3)
    • August 2013 (1)
    • July 2013 (1)
    • June 2013 (2)
    • May 2013 (2)
    • April 2013 (3)
    • February 2013 (3)
    • January 2013 (2)
    • November 2012 (1)
    • October 2012 (1)
    • August 2012 (2)
    • July 2012 (3)
    • June 2012 (3)
    • May 2012 (3)
    • April 2012 (1)
    • March 2012 (2)
    • December 2011 (4)
    • November 2011 (1)
    • June 2011 (4)
    • May 2011 (4)
    • April 2011 (1)
    • March 2011 (1)
    • February 2011 (4)
    • January 2011 (4)
    • December 2010 (2)
    • November 2010 (4)
    • October 2010 (3)
    • September 2010 (2)
    • August 2010 (1)
    • July 2010 (1)
    • June 2010 (1)
    • May 2010 (1)
    • April 2010 (2)
    • March 2010 (4)
    • February 2010 (1)
    • January 2010 (1)
    • December 2009 (1)
    • November 2009 (1)
    • October 2009 (2)
    • September 2009 (3)
  • Blogroll

    • Embedded Gurus
    • Jack Ganssle
    • James Grenning’s Blog
    • Peter Bushell
    • Whaleygeek
You are visitor 01402860 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.