How can I combine a directory and file path to create a new path?

Question:

My script have to work in Linux and Windows. And the script receives two pattern strings as arguments:

  1. C:test or /usr/local/test (without suffix)
  2. C:test or /usr/local/test/ (with suffix '' or '/')

The following code works without problems, but I do not want to use specific character '/'. Because it close to bug, I think.
Do you have some idea?

# -*- coding: utf-8 -*-

import argparse

def parse_args():
    parser = argparse.ArgumentParser(description='This script is ...')
    parser.add_argument('--confdir', type=str, required=True)
    parser.add_argument('--outdir', type=str, required=True)
    return parser.parse_args()

if __name__ == '__main__':
    args = parse_args()
    # "C:/test" or "C:/test/" in Windows
    # "/usr/local/test" or "/usr/local/test/" in Linux
    print(args.confdir)

    f = open(args.confdir + "/" + 'sample.txt')
    print(f.read())
Asked By: Maiko Ohkawa

||

Answers:

Change:

open(args.confdir + "/" + 'sample.txt') 

to

open(args.confdir + os.sep + "sample.txt')
Answered By: Sting Jia

Using os.path.join is the best approach, replacing:

open(args.confdir + "/" + 'sample.txt') 

with:

open(os.path.join(args.confdir, 'sample.txt'))

os.path.join will properly prevent doubled separators, so it doesn’t matter if confdir ends in a slash or not, it will produce output with only a single slash.

In rare circumstances, you may want to work with os.sep and os.altsep instead, but that’s uncommon. The main reason you might use them would be to explicitly lstrip away incorrect leading slashes on a path component; trailing slashes don’t matter (os.path.join dedups for you), but leading slashes are treated as the beginning of an absolute path, and throw away previous components.

Answered By: ShadowRanger

You could use an object such as pathlib.Path that takes care of the trailing path separator automatically e.g.:

#!/usr/bin/env python3
import argparse
import pathlib

parser = argparse.ArgumentParser()
parser.add_argument('--confdir', type=pathlib.Path, default='.')
args = parser.parse_args()
print(args.confdir)
path = args.confdir / 'sample.txt'
print(path)
print(path.read_text())
Answered By: jfs
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.