-2

I want create text file in current directory

i wrote this code and it worked in vscode:

import os
p = __file__
p = str(p)
f = open(p + '.txt', 'a')
f.write('hello world')

But it does not create a text file when I use pyinstaller !!!

Sabil
  • 3,750
  • 1
  • 5
  • 16
  • If you want to create a file, use ‘w’ instead of ‘a’. ‘a’ means “append”, so you are appending to a file rather than creating it. – Roni Sep 04 '21 at 20:23
  • @Roni `a` also creates a new file if one doesn't exist already – Matiiss Sep 04 '21 at 20:24
  • I can't reproduce the issue (Windows 8.1, Python 3.8.2), I converted the file to an `.exe` and it worked fine, what exactly is the issue? are there any errors (run from `cmd` to check)? – Matiiss Sep 04 '21 at 20:34
  • 1
    Once packaged with PyInstaller, where exactly do you expect it to write this file? Where are you looking for it? What options are you supplying to PyInstaller (one-file, one-folder, etc.), and have you tried printing (to console) the file name / path you're trying to write to? – CrazyChucky Sep 04 '21 at 20:42
  • @Matiiss, ok, good to know, thanks! – Roni Sep 05 '21 at 13:25

1 Answers1

-1

Take a look at the code below. You need to specify the correct file permissions when using the open() function.

import os
p = __file__
p = str(p)
try: # in the case that the file does not exist, you can use a try block to catch the error.
    f = open(p + '.txt', 'w') # a works as well instead of w.
    with f: 
        f.write('hello world')
except IOError: 
    print("Failed to open file.") 
Mark Park
  • 13
  • 1
  • 6
  • welll, it is not really an answer, you just basically copied what OP had written and just changed one letter that shouldn't make a difference anyways so I don't see how this has any value, also probably better to use `with` to open and close files, also the file has to be closed – Matiiss Sep 04 '21 at 20:30
  • I more of mean to use `with open() as file` so that the closing and errors is handled automatically or sth, ok this works but you don't need to then close the file yourself – Matiiss Sep 04 '21 at 20:35
  • 1
    kind of except this answer doesn't answer the question really still. the try except is kinda useless because it shouldn't fail at creating the file more of there would be an OS error denying the creation of a file (or antivirus could prevent that) and also I couldn't even reproduce the issue with OP's code, there almost even isn't an issue, did you try using `pyinstaller` on the OP's code and run it and see if it creates the file? (btw I didn't downvote) – Matiiss Sep 04 '21 at 20:40
  • No, I didn't receive an error with the person's code so I assumed that he is attempting to open a file that already exists, hence I added the try and except block. @Matiiss – Mark Park Sep 04 '21 at 21:03