Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

open() is not working for hidden files python

Tags:

python

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.

like image 251
user2460869 Avatar asked Jul 04 '13 01:07

user2460869


People also ask

Why my hidden file is not opening?

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".

How do I open hidden files in CMD?

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.


1 Answers

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')
... 
>>>
like image 149
Jared Avatar answered Oct 20 '22 23:10

Jared