techydesigner techydesigner - 2 months ago 8
Python Question

Python dedicated class for file names

I am writing a program that utilises a large number of files. Does Python feature an inbuilt class for file paths, or does one have to be implemented by the user (like below):

class FilePath:
def __init__(path):
shazam(path)

def shazam(self, path):
""" something happens, path is formatted, etc """
self.formatted_path = foobar


Why would it be useful?

Suppose the program and its data is copied to a different operating system. The class could modify itself on launch to support the a different path separator.

Why not just write it yourself?

Someone might have already written a class in the standard Python library.

Answer

Python has several cross platform modules for dealing with the file system, paths and operating system.

The os module specifically has an os.sep character.

os.path.join() is OS-aware and will use the correct separator when joining paths together.

Additionally, os.path.normpath() will take any path and convert the separators to whatever the native OS supports.