pythonwindowspathos.path

how to open file in windows with python?


I'm passing the file name trough sys.argv with slashes not backslashes . I'm using os.path.normpath and os.path.join but when trying to open the file I get an exception no such file or directory: and the path is with double backslashes. I'm searching for the solution for hours but nothing works.

I'v tried every tutorial I could find on google and I just keep getting the same problem. I just keep getting double back slashes. I've tried also just hardcoding the path like in example.

filepath = os.path.normpath(os.path.join('D:/dir1/dir2/dir3', 'myfile.txt'))
try:
    my_file = open(filepath, 'w+')
except Exception as e:
    print('Cannot create/open file w+!\n{}'.format(e))

I've need to be able to open the file.


Solution

  • In python scripts it works with:

    file_path =  os.path.join(os.path.abspath(os.path.dirname(__file__)), 'config.ini')
    

    But if I need to build a program with py2exe the __file__ doesn't work and I use:

    file_path =  os.path.join(os.path.abspath(os.path.dirname(sys.argv[0])), 'config.ini')
    

    Hope this helps some one.