Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create the directory automatically if it doesn't exist #70 #72

Closed
wants to merge 4 commits into from
Closed

Conversation

HyoungSooo
Copy link
Contributor

Create PR for #70

This PR is add decorator and test code for create new folder if it dose not exist.

def create_folder_if_not_exists(func) -> None:

    def wrapper(*args, **kwargs) -> None:
        try:
            filepath = args[0]
        except:
            filepath = kwargs["filepath"]
        folder = os.path.dirname(filepath)
        if not os.path.exists(folder) and folder != "":
            os.makedirs(folder)
        return func(*args, **kwargs)

    return wrapper

The reason why the try except statement is used is because other methods that call the write_csv function sometimes pass the filepath into args and sometimes kwarg.

usage

@create_folder_if_not_exists
def write_csv(filepath: Path, records: List[dict], schema: dict, **kwargs: Any) -> int:
    """Write a CSV file."""
    if "properties" not in schema:
        raise ValueError("Stream's schema has no properties defined.")

    keys: List[str] = list(schema["properties"].keys())
    with open(filepath, "w", encoding="utf-8", newline="") as fp:
        writer = csv.DictWriter(fp, fieldnames=keys, dialect="excel", **kwargs)
        writer.writeheader()
        for record_count, record in enumerate(records, start=1):
            writer.writerow(record)

    return record_count

If there is a better way please let me know

Copy link

sonarcloud bot commented Feb 16, 2024

Quality Gate Passed Quality Gate passed

Issues
0 New issues

Measures
0 Security Hotspots
No data about Coverage
No data about Duplication

See analysis details on SonarCloud

@HyoungSooo HyoungSooo closed this Feb 16, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant