1

I have some text files in a directory (say A/b1/b2/File.txt), while my script is in another directory (say A/m1/m2/Program.py). How do I load the text file from the python script.

I am not looking to import any module, or function from other python script, but loading a non-python file(like text or csv) from some parallel location using my python script.

somsom
  • 21
  • 1
  • 3
  • Is there any reason why a relative path is not working for you: `open("../../b1/b2/)`? – FlyingTeller Jun 05 '18 at 08:08
  • i tried relative path but it says "no such file or directory" error, also inside b2 i have multiple file so tried using os.chdir – somsom Jun 05 '18 at 08:35
  • I would stick with the solution by Super S then as determining the path from `__file__` is your safest option in my opinion – FlyingTeller Jun 05 '18 at 08:58

2 Answers2

0

You can just enter the full address:

File=open("C:\A\b1\b2\File.txt") #Assuming you're using windows.

If you don't know the full address, then you may need to import from a library.

from os.path import realpath
from os.path import dirname
Path=realpath(__file__)
while Path.split("\\")[-1]!="A":Path=dirname(Path)
Path+="\\b1\\b2\\File.txt"
File=open(Path)
Programmer S
  • 429
  • 7
  • 21
  • yes that C:\ part in the solution that is absolute path but i dont have absolute path with me and it has to happen in a project at run time, also there will be multiple files and not just one text file(but that i can take care of). thanks – somsom Jun 05 '18 at 08:30
  • @SourabhMehta I've added an example which uses a library, as I don't know how to do this without one. If you don't know the full address, then it would have been a good idea to mention this in your question. – Programmer S Jun 05 '18 at 08:49
0

just specify the path and open it.

file_to_open =  r'A/b1/b2/somefile.csv'  # don't forget the 'r' here to prevent backslash issues

with open(file_to_open, 'r') as file:
     df1 = pd.read_csv(file)
sudonym
  • 3,788
  • 4
  • 36
  • 61
  • Are you sure that is correct? I would have thought that doing that would just open `"A/m1/m2/A/b1/b2/somefile.csv"`, which won't exist. – Programmer S Jun 05 '18 at 08:54
  • yes, that works. add the COMPLETE path and try it out - if it works, please accept my answer. – sudonym Jun 05 '18 at 08:55