Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
file Problem
#1
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
Reply
#2
You do that right. But it does not work? Then it will show an error message. Show us that error message please.
Reply
#3
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')
faraz_h likes this post
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020