-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 !!!

5
  • 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. Commented Sep 4, 2021 at 20:23
  • @Roni a also creates a new file if one doesn't exist already Commented Sep 4, 2021 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)? Commented Sep 4, 2021 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? Commented Sep 4, 2021 at 20:42
  • @Matiiss, ok, good to know, thanks! Commented Sep 5, 2021 at 13:25

1 Answer 1

-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.") 
Sign up to request clarification or add additional context in comments.

4 Comments

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
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
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)
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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.