简体   繁体   中英

Can i shorten a file location to the .py files location

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM