9

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.

user2460869
  • 471
  • 1
  • 8
  • 15

1 Answers1

20

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')
... 
>>>
Jared
  • 25,627
  • 7
  • 56
  • 61