There is a structure: A -testfile.py B -textfile.txt

In the testfile.py file you need to read all the textfile.txt data

I tried to specify through a relative path, but it did not work my_file = open ("../ b / textfile.txt", "r")

  • What did not work out? How did you determine what did not work out? - titov_andrei
  • When launched on Jenkins, it returns> my_file = open ("../ b / textfile.txt", "r") E IOError: [Errno 2] No such file or directory: '../b/textfile.txt' - Sergey
  • It is better to write the full path. - Arnial
  • Unfortunately, using the absolute path (if you are talking about it) is not possible. - Sergey
  • Related question: Current directory in Python (note the pkgutil and pkg_resources modules) - jfs

3 answers 3

If you need to open a file relative to the script being run, you can take the path to it from the built-in variable __file__ :

 import os print os.path.join(os.path.dirname(__file__),'..','b','textfile.txt') 
     import os a = 'dir/dd\er//wq\\qwe' n = os.path.join(os.getcwd(), os.path.normpath(a)) print(n) with open(os.path.join(n, 'f1'), 'r') as fr, open(os.path.join(n, 'f2'), 'w') as fw: fw.write(fr.read()) 

    out:

     C:\Scripts\python\2016\4\dir\dd\er\wq\qwe 

      Check os.chdir , perhaps the path is not built initially from the path that you mean. well and try to build a relative path through os.path.join