Error getting relative path in python

2

I try to get the relative path to open a txt document using the following code:

imports os

filePath = os.path.relpath('../ProyectoLenguajeInterprete/Test')

txt = open(filePath)
print "Content for: %r:" % filePath
print txt.read()

But he throws me the following error:

  

Traceback (most recent call last):
  File "C: \ Users \ team \ Documents \ NetBeansProjects \ ProjectInterpreteChange \ src \ projectinterguageinterprete.py", line 114, in < module >   txt = open (filePath)
  IOError: [Errno 2] No such file or directory: '.. \ Interpreter Project \ Test'

    
asked by Efrainrodc 02.05.2017 в 23:59
source

2 answers

2

The problem is that your relative path points to a nonexistent directory.

If the source is being interpreted in

"C:\Users\equipo\Documents\NetBeansProjects\ProyectoLenguajeInterprete\src\proyectolenguajeinterprete.py"

Then the path .. / points to src/ . Also, the path ../../ will point to src/ProyectoLenguajeInterprete

Here you could call the file directly, defining filePath = os.path.relpath('../../Test') which is more elegant.

If the exercise requires the ProyectoLenguajeInterprete string in the variable filePath then you must upload one more level in the relative path:

filePath = os.path.relpath('../../../ProyectoLenguajeInterprete/Test')

When you use relative paths, especially when you define submodules in a directory structure, remember that CWD where you anchor the path is the directory where the source of the current routine is being interpreted.

    
answered by 03.05.2017 / 04:05
source
1

I think the problem may be that you lack the file extension if you have it. In your ProyectoLenguajeInterprete directory there should be a file, something like Test.txt no Test simply:

filePath = '../ProyectoLenguajeInterprete/Test.txt'

txt = open(filePath)
print "Content for: %r:" % filePath
print txt.read()
txt.close()
    
answered by 03.05.2017 в 00:47