0

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?

2 Answers 2

2

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())
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

You might want to add the rest of the code to safely create parent directories.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.