Get Path


import os
os.getcwd()

# or
from pathlib import Path
Path.cwd()
Path.home() # for home folder

Create a file [by creating non-existing parent folders recursively]

import os

filename = "/foo/bar/baz.txt"
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, "w") as f:
    f.write("FOOBAR")
from pathlib import Path

save_output_path = "/tmp/gradio/answers.txt"
path = Path(save_output_path)
path.**parent**.mkdir(exist_ok=True, parents=True)
path.touch(exist_ok=True)

Remove a file

from pathlib import Path

Path("/tmp/app_logs.log").unlink(missing_ok=True)

Get Suffix of a file

from pathlib import Path

Path("./data/app_logs.pdf").suffix

Run python inside

""" Main application logic (e.g. initializing models, handling input/output) """
if __name__ == "__main__":
    try: 
        from src.presentation.ui import app_ui
        app_ui.run_ui()
    except ModuleNotFoundError as e:
        # print(f'{e}, please run:\\033[92m python -m src.main_ui \\033[0m')
        import os
        os.system("python -m src.main_ui")

Check if the path is a directory

from pathlib import Path

input_dir_path = "./data/example_inputs/_attachments"
if not Path(input_dir_path).is_dir():
   raise ValueError(f"Given path {input_dir_path} is not a directory.")

Check if the path is a file

from pathlib import Path

input_file_path = "./data/example_inputs/attachment1.pdf"
if not Path(input_file_path).is_file():
   raise ValueError(f"Given path {input_dir_path} is not a file.")

Check if the path exists

from pathlib import Path

input_path = "/tmp/gradio"
if not Path(input_path).exists():
   raise ValueError(f"Given path {input_dir_path} does not exist.")

Remove Content of a folder with os

def refresh_db():
    # remove content of 'data/chroma_data/'
    db_dir = "data/chroma_data"
    if os.path.exists(db_dir):
        for file in os.listdir(db_dir):
            # if its a folder remove it as well
            if os.path.isdir(os.path.join(db_dir, file)):
                shutil.rmtree(os.path.join(db_dir, file))
            else:
                os.remove(os.path.join(db_dir, file))
        

Iterate over a folder files (json) and join them