0

first post here so sorry if it's hard to understand. Is it possible to shorten the directory in python to the location of the .py file?. For example, if I wanted to grab something from the directory "C:\Users\Person\Desktop\Code\Data\test.txt", and if the .py was located in the Code folder, could I shorten it to "\data\test.txt". I'm new to python so sorry if this is something really basic and I just didn't understand it correctly.

I forgot to add i plan to use this with multiple files, for example: "\data\test.txt" and \data\test2.txt

2 Answers2

2
import os

CUR_FILE = os.path.abspath(__file__)
TARGET_FILE = "./data/test.txt"

print(os.path.join(CUR_FILE, TARGET_FILE))

With this, you can move around your Code directory anywhere and not have to worry about getting the full path to the file. Also, you can run the script from anywhere and it will work (you don't have to move to Code's location to run the script.

fmigneault
  • 341
  • 3
  • 5
1

You can import os and get current working directory ,this will give you the location of python file and then you can add the location of folder data and the file stored in that ,code is given below

import os
path=os.getcwd()
full_path1=path+"\data\test.txt"
full_path2=path+"\data\test2.txt"
print(full_path1)
print(full_path2)

I think this will work for your case and if it doesn't work then add a comment

Saksham Kushwaha
  • 274
  • 1
  • 18
  • 2
    Will this work with multiple files?. I forgot to add this, an example should be in the edit. – 64Terabytes Sep 18 '20 at 03:27
  • 1
    You can give separate variable for both files like for the first file you can add "\data\test.txt" to path variable and for the second one you can name another variable and add "\data\test2.txt" to path variable edits has been made to previous answer – Saksham Kushwaha Sep 18 '20 at 03:30
  • I found another post that fixed my problem, thanks for your help though. – 64Terabytes Sep 22 '20 at 23:50