How to get full path of a file?
#1
I have been working on a batch script that needs to resolve the full path of a file for processing. Essentially, what I'm trying to achieve is for the command line to print the absolute path of a file given its relative path or filename. I've stumbled across several solutions that use different command-line utilities, but I haven't found one that fits my needs perfectly. For example, consider the file file.txt which is located in the directory /nfs/an/disks/jj/home/dir/. If I'm currently in the dir directory, I want to be able to issue a command like the following and have it return the file's full path:


And the output should be exactly:


Is there a robust and cross-platform approach to doing this? A snippet of code that can be used directly in my script would be ideal.
Reply
#2
Here's a simple and straightforward command you can use on a Unix-like system. This approach uses the pwd command along with parameter expansion to get the job done. If the file is in the current directory, you can use:

Code:
echo "$(pwd)/file.txt"

This will concatenate the output of pwd, which is the current directory path, with the filename, giving you the full path to the file. It's simple and does not require any additional tools or parsing.
Reply
#3
The solution provided is specific to Unix-like systems and would not work in a Windows command prompt environment. For a cross-platform solution, using a scripting language might be more suitable. Here's an example using Python, which is widely available on many operating systems:

Code:
def get_full_path(filename):
    return os.path.abspath(filename)
print(get_full_path('file.txt'))

By using the os.path.abspath function, Python takes care of resolving the absolute path for you, making it compatible across different operating systems, provided that Python is installed.
Reply
#4
The Python solution appears to be the most versatile option, given that it abstracts away the platform specifics. I'll integrate this into my batch script by invoking the Python interpreter to run this piece of code. To complete the batch, the Python script will need to be saved as a separate file, which the batch script can call with the filename as an argument.
Here is the complete Python script for resolving the full path of a given file:

Code:
def get_full_path(filename):
    return os.path.abspath(filename)
if __name__ == '__main__':
    if len(sys.argv) != 2:
    print("Usage: {} <filename>".format(sys.argv[0]))
else:
    print(get_full_path(sys.argv[1]))

To use this script, make sure to save it as `get_full_path.py` and call it from your batch script or directly from the command line like this:


This will print the full path to `file.txt`, regardless of the platform.
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)