Search code examples
pythonpyinstaller

Issue writting to file with pyinstaller


So an update, I found my compile issue was that I needed to change my notebook to a py file and choosing save as doesn't do that. So I had to run a different script turn my notebook to a py file. And part of my exe issue was I was using the fopen command that apparently isn't useable when compiled into a exe. So I redid the code to what is above. But now I get a write error when trying to run the script. I can not find anything on write functions with os is there somewhere else I should look?

Original code:

import requests
import json
import pandas as pd
import csv
from pathlib import Path



response = requests.get('url', headers={'CERT': 'cert'}, stream=True).json()
json2 = json.dumps(response)
f = open('data.json', 'r+')
f.write(json2)
f.close()

Path altered code:

import requests
import json
import pandas as pd
import csv
from pathlib import Path



response = requests.get('url', headers={'CERT': 'cert'}, stream=True).json()
json2 = json.dumps(response)
filename = 'data.json'
if '_MEIPASS2' in os.environ:
    filename = os.path.join(os.environ['_MEIPASS2'], filename)
fd = open(filename, 'r+')
fd.write(json2)
fd.close()

The changes to the code allowed me to get past the fopen issue but created a write issue. Any ideas?


Solution

  • If you want to write to a file, you have to open it as writable.

    fd = open(filename, 'wb')
    

    Although I don't know why you're opening it in binary if you're writing text.