简体   繁体   中英

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, ie, 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')

Ie, 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 ?

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())

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM