Home python python: reading a TXT file from another folder relative to the start

python: reading a TXT file from another folder relative to the start

Author

Date

Category

There is a structure:
A.
-TestFile.py.
B.
-TextFile.txt

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

tried to point through the relative path, but it did not work
My_File = Open (“../ b / textfile.txt”, “R”)


Answer 1, Authority 100%

If you need to open the file relative to the script running, 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')

Answer 2

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

Answer 3

Check the Os.Chdir , it is possible a path to be built initially not from the path you mean. Well, try to build a relative path through os.path.join

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions