Home > OS >  Unexpected behavior: writing to JSON and .csv in Python function
Unexpected behavior: writing to JSON and .csv in Python function

Time:03-25

Background - I have a .py script which runs perfectly when run in JupyterLab (specifically both a JSON and .csv file are written (through separate functions) to the same dir as the script, which is on my C: drive), however not so much, since I started development in PyCharm and try writing the files to a network drive.

Issue - the 2x separate functions in my script take a JSON file and pandas dataframe respectively and write to a JSON and .csv file. As I haven't specified a file path in either case, I assume (like is the behavior when run in JupyterLab) the files should be written to the same dir as the script. Unfortunately the files simply do not write, and my code runs without error

Functions in question - here are the functions that write the JSON and .csv:

Function for .JSON:

# Function that writes response to a .json file and returns variable holding data.
def response_writer():
    api_response = api_call()
    timestr = datetime.datetime.now().strftime("%Y-%m-%d")
    filename = 'financial_accounts_api_response_' timestr '.json'
    with open(filename, 'w') as output_data:
        json.dump(api_response, output_data)
        print("-------------------------------------------------------\n",
              "API RESPONSE SAVED:", filename, "\n-------------------------------------------------------")
    return api_response

Function for .csv:

# Function that writes to .csv file.
def main():
    financial_accounts_df = dataframe_transformation()

#   Writing dataframe to .csv
    timestr = datetime.datetime.now().strftime("%Y-%m-%d")
    filename = 'financial_accounts_' timestr '.csv'

    financial_accounts_df.to_csv(filename, encoding='utf-8', index=False)

if __name__ == "__main__":
    main()

Useful information:

  1. Script location - this script that works in JupyterLab is saved on my C: drive. However the identical script which doesn't work as expected is saved on a network drive, in case this might be causing an issue. Note: it goes without saying, I have the necessary perms for this drive.

Help: are there any suggestions why my functions are not performing as intended i.e., the respective .JSON and .csv are not saving? Should I be implicit with specifying a file path to save them?

CodePudding user response:

Part of my script reads a .ini file that contains API credentials, which are used to make an API call; the response is critical in then saving the .JSON and .csv file.

PyCharm did not alert me of this (something to investigate seperately), however the .ini file was missing elements that made it readable.

  • Related