The main idea is to get script full path with readlink or realpath command and later extract directory path with dirname. There are other ways how to get executed script directory path, we will focus on 2 of them. SCRIPT_DIR=$(cd "$(dirname "$")" &> /dev/null & (pwd -W 2> /dev/null || pwd))Įcho $SCRIPT_DIR // Format under Windows: C:/test If you want to get a solution that returns Windows or Linux formatted path try this solution: #!/bin/bash chdir()).Script directory path printed in Bash under Windows. getcwd()) and change it into a different directory (. Below illustrates how to find your CWD (. Python module os provides utilities for displaying and modifying your current working directory. See this screen shot and and the next section for how to work with your CWD setting in Python shell. (Not recommended, since your shell's CWD may change.) Change your CWD to the file's directory, or.Unless your file happens to be in your CWD, you have two options: (Mac users should see this FAQ for how to change your setting.) In OS-X, it is usually '/Users/username/Documents' where username is your user ID. ![]() In Windows, the default location is often 'C:/program Files (x86)/Python35-32' (which is inconvenient - see this "Basic Configurations" page or this FAQ for how to change it). In your shell, the initial CWD setting varies by system. Myfile = open( 'alice.txt') # alice.txt is in the same dir as foo.py Therefore, you can refer to a file in a script by its name only provided that the file and the script are in the same directory. When you execute your script, your CWD is set to the directory where your script is. Also, your Python has different initial CWD settings depending on whether you are working with a Python script or in a shell environment. But bear in mind that your CWD may change. This means that a name-only reference will be successful only when the file is in your Python's CWD. But if your file reference does not start from the top (e.g., 'alice.txt', 'ling1330/alice.txt'), Python assumes that it starts in the CWD (a " relative path"). So far we have been using the absolute path, which begins from the topmost directory. You can think of it as the folder your Python is operating inside at the moment. The concept of Current Working Directory (CWD) is crucial here. ![]() However, you might have seen files called by their name only, e.g., 'alice.txt' in Python. So, using the full directory path and file name always works you should be using this method. That way, everything in the string is interpreted as a literal character, and you don't have to escape every backslash.įile Name Shortcuts and CWD (Current Working Directory)
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |