Glen Pierce
Glen Pierce

Reputation: 4801

How to open a file given its absolute path in Python 3.x

This Python code is generating a FileNotFoundError:

path = prog = os.path.abspath(__file__).split(os.sep) 
f = open(os.path.join(os.path.dirname(__file__), '...\\logFiles\\logDump.txt'),"a")

I receive this error:

FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Root\\svn\\trunk\\src\\test\\python\\...\\logFiles\\logDump.txt'

C:\Root\svn\trunk\src\test\python\logFiles\logDump.txt definitely exits. What's going on with the elipsis? If I remove it, I get this error:

FileNotFoundError: [Errno 2] No such file or directory: 'C:\\logFiles\\logDump.txt'

It seems like something's wrong with the String I'm eventually passing to open(), but I'm not sure what it should look like. My OS is Windows 10.

Upvotes: 2

Views: 6799

Answers (1)

Stephen Rauch
Stephen Rauch

Reputation: 49784

You might want this:

os.path.join(os.path.dirname(__file__), '..\\logFiles\\logDump.txt')

which would equivalent to this:

os.path.join(os.path.dirname(os.path.dirname(__file__)), 'logFiles\\logDump.txt')

Or you might simply want this (it is not clear from your question):

os.path.join(os.path.dirname(__file__), 'logFiles\\logDump.txt')

Upvotes: 1

Related Questions