I want to create and write a .txt file in a hidden folder using python. I am using this code:
file_name="hi.txt"
temp_path = '~/.myfolder/docs/' + file_name
file = open(temp_path, 'w')
file.write('editing the file')
file.close()
print 'Execution completed.'
where ~/.myfolder/docs/ is a hidden folder. I ma getting the error:
Traceback (most recent call last):
File "test.py", line 3, in <module>
file = open(temp_path, 'w')
IOError: [Errno 2] No such file or directory: '~/.myfolder/docs/hi.txt'
The same code works when I save the file in some non-hidden folder.
Any ideas why open() is not working for hidden folders.
Option 1. Open the folder that contains the hidden files, go to "View", and check "Hidden items". Option 2. Go to "Control Panel" > "File Explorer Options", go to the "View" tab, and check "Show hidden files, folders, and drives".
For the quickest option, you can show hidden files using the keyboard shortcut CTRL + H. You can also right-click anywhere in a folder and check the Show hidden files option at the bottom.
The problem isn't that it's hidden, it's that Python cannot resolve your use of ~
representing your home directory. Use os.path.expanduser
,
>>> with open('~/.FDSA', 'w') as f:
... f.write('hi')
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: '~/.FDSA'
>>>
>>> import os
>>> with open(os.path.expanduser('~/.FDSA'), 'w') as f:
... f.write('hi')
...
>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With