如何在Python3.x中打开给定绝对路径的文件

如何在Python3.x中打开给定绝对路径的文件,python,python-3.x,Python,Python 3.x,此Python代码正在生成FileNotFoundError: path = prog = os.path.abspath(__file__).split(os.sep) f = open(os.path.join(os.path.dirname(__file__), '...\\logFiles\\logDump.txt'),"a") 我收到这个错误: FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Root\\sv

此Python代码正在生成FileNotFoundError:

path = prog = os.path.abspath(__file__).split(os.sep) 
f = open(os.path.join(os.path.dirname(__file__), '...\\logFiles\\logDump.txt'),"a")
我收到这个错误:

FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Root\\svn\\trunk\\src\\test\\python\\...\\logFiles\\logDump.txt'
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\logFiles\\logDump.txt'
C:\Root\svn\trunk\src\test\python\logFiles\logDump.txt肯定存在。省略是怎么回事?如果将其删除,则会出现以下错误:

FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Root\\svn\\trunk\\src\\test\\python\\...\\logFiles\\logDump.txt'
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\logFiles\\logDump.txt'
我最终传递给open()的字符串似乎有问题,但我不确定它应该是什么样子。我的操作系统是Windows 10。

您可能需要:

os.path.join(os.path.dirname(__file__), '..\\logFiles\\logDump.txt')
这相当于:

os.path.join(os.path.dirname(os.path.dirname(__file__)), 'logFiles\\logDump.txt')
或者您可能只是想要这个(您的问题不清楚):


在你的道路上,
是怎么回事?我不太确定。如果我离开它,我会得到FileNotFoundError:[Errno 2]没有这样的文件或目录:“C:\\Root\\svn\\trunk\\src\\test\\python\\…\\logFiles\\logDump.txt”,但如果我删除它,我会得到FileNotFoundError:[Errno 2]没有这样的文件或目录:“C:\\logFiles\\logDump.txt”。我不知道为什么没有它就不能连接。我认为os.path.join()有必要将路径的开头连接到结尾。f=open(os.path.join(os.path.dirname(os.path.dirname(file)),'logFiles\\logTextSuperDump.txt'),“a”)生成FileNotFoundError:[Errno 2]没有这样的文件或目录:“C:\\Root\\svn\\trunk\\src\\test\\logFiles\\logDump.txt”这似乎非常接近正确。我是否使用了错误的“\\”字符?C:\Root\svn\trunk\src\test\logFiles\logDump.txt该文件不存在。我缺少一个中间目录。好的,这个答案是正确的,但我没有注意到C:\\Root\\svn\\trunk\\src\\test\\logFiles\\logDump.txt在代码更改后缺少一个目录,即C:\\Root\\svn\\trunk\\src\\test\\python\\logFiles\\logDump.txt。一旦我将代码改为f=open(os.path.join(os.path.dirname(os.path.dirname(file)),'python\\logFiles\\logDump.txt'),'a'),它就运行得很好。谢谢:)如果您必须将
python
放回,那么使用第三个示例,从文件路径中删除一个目录。