Python Forum
file Problem - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: file Problem (/thread-33275.html)



file Problem - faraz_h - Apr-12-2021

hi
I can not create a file or write anything inside the file on mac OS

my cod is :

test = open("test.txt","w")
test.write('test hello')
test.close()
Doh
mac os : 11.2.3
python : 3.9.4
idle : VSCODE


RE: file Problem - ibreeden - Apr-12-2021

You do that right. But it does not work? Then it will show an error message. Show us that error message please.


RE: file Problem - Larz60+ - Apr-12-2021

It's possible that your file was not written where you expected it was going to be written.
That can be assured if you set the starting directory, or specify a full path (as below). The statement shown here
guarantees that the starting directory is the same as that of the script.
Also, using 'with' on your open statement will automatically close the file at end and is the preferred method to use:

import os

os.chdir(os.path.abspath(os.path.dirname(__file__)))
with open("test.txt","w") as test:
    test.write('test hello')