0

I need to open and read a text file that works with Mac. I wrote the code below and it works fine: it opens a file dialog, I can pick a text file, and it stores the content in two different variables (one for reading the content as one big string and another with line breaks). Then, I perform several operations by calling the variables with no problem. However, when I create a standalone application (with py2app), the app crashes when it has to read the content.

Everything works fine with Windows (even when launching the app from the .exe file), but it does not work from the standalone Mac application. I also wrote the data[0] (the path of the file picked by the user) in a pickle file and I can see that the path is there, so it is just the open(data[0]).read() or .readlines() that don't work.

My MacOS version is 10.15.6.

data = QtWidgets.QFileDialog.getOpenFileName(self, 'Select Text File', os.getcwd(), 'Text Files (*.txt)')
    if data != ('', ''):
        data_lines = open(data[0]).readlines()
        data_string = open(data[0]).read()
Miro
  • 1
  • 1
    Maybe unrelated to your actual problem but consider using `with open(...)` anywhere you can. – Jan Aug 06 '20 at 21:35
  • Does this answer your question? [How to Open a file through python](https://stackoverflow.com/questions/19508703/how-to-open-a-file-through-python) – Sanoj Aug 06 '20 at 21:49

1 Answers1

0

Try using the with statement. Here's an example:

with open('file_name.txt') as file:
    info = file.read()

If you want to write to the file:

with open('file_name.txt', 'w') as file:

Hope this helps and good luck!

Asif Ally
  • 41
  • 4
  • Unfortunately, the issue persists. I switched to "with open" method but still the same problem with the standalone application, while when I run the python file through the terminal in Visual Studio Code, it works perfectly. I've kept searching but couldn't find anything that works – Miro Aug 07 '20 at 03:47