Gabriel
Gabriel

Reputation: 42349

Save file to output folder creating it if it does not exist

I'm using the pathlib library to handle I/O in my script. I read a file with the path:

PosixPath('input/ADE/data_f34.dat')

The parent folder input/ is fixed, but neither the sub-folder (ADE) nor the file's name are fixed, i.e., they change with each iteration. I need a general to store a new file with the same name, to the path:

PosixPath('output/ADE/data_f34.dat')

I.e., respecting the sub-folder and the file's names, but changing input/ to output/. The output folder always exists, but I don't know a priori if the sub-folder output/ADE/ exists so I need to create if it does not. If a file with the same name already exists, I can simply overwrite it.

What is the proper way to handle this with pathlib?

Upvotes: 0

Views: 146

Answers (2)

hurlenko
hurlenko

Reputation: 1425

You can use relative_to:

from pathlib import PosixPath

filename = PosixPath('input/ADE/data_f34.dat')
output_dir = PosixPath('output')

path = output_dir / filename.relative_to('input')
path.parent.mkdir(parents=True, exist_ok=True)

print(path)

Prints

output/ADE/data_f34.dat

Upvotes: 1

Balaji Ambresh
Balaji Ambresh

Reputation: 5012

Is this what you're looking for?

import pathlib

src = pathlib.PosixPath('input/ADE/data_f34.dat')
dst = pathlib.Path('output', *src.parts[1:])
dst.parent.mkdir(parents=True, exist_ok=True)
with open(dst, 'w') as d, open(src) as s:
    d.write(s.read())

Upvotes: 2

Related Questions