I. Get file path realization
1.1 Get the current file path
import os current_file_path = __file__ print(f"current_file_path: {current_file_path}")
There's actually a problem with the __file__ variable, when the file is the called file __file__ is always the absolute path of the file; but when the file is the directly executed file, __file__ is not always the absolute path of the file, but rather the path that you passed to python when you executed the file. For example, if you are executing python as xxx/, then the value of __file__ is xxx/.
You can use the following more uniform way to get the file path:
import inspect current_file_name = (()) print(f"current_file_name: {current_file_name}")
1.2 Getting the file path of the calling file
Sometimes we want to get the file path of the parent file that calls the current file, this can be achieved by the following code:
import inspect def be_call_fun(): # stack() returns a list of call stacks. frame_stack = () # 0 is the stack that identifies the current function, 1 is the stack that identifies the previous function, and so on. # That is, the value is not necessarily 1, depending on what level of the function you want to get its file path at caller_frame = frame_stack[1] caller_file_path = caller_frame.filename # The filename is still the current filename because the current calling function and the called function are placed in the same file. # The calling and called functions can be observed in separate files. print(f"caller_file_path: {caller_file_path}") def caller_fun(): be_call_fun() if __name__ == "__main__": caller_fun()
II. Access to catalogs
2.1 Getting the current working directory
The so-called current working directory is the folder where the shell is located when you execute the python command to execute a python file.
import os current_working_dir = () print(f"current_working_dir: {current_working_dir}")
2.2 Getting directories by path
The first section we have borrowed the introduction of several ways to get the path of the file, to get the corresponding file is located in the folder, you can directly with the help of these path + () to achieve.
import os # Absolute path to the file current_file_path = __file__ # Extract directories from absolute paths with the help of dirname(). current_file_dir = (current_file_path) print(f"current_file_dir: {current_file_dir}") # Similarly you can extract filenames from absolute paths with the help of basename(). # current_filename = (current_file_path) # It is also recommended to use () for path splicing, so that you don't have to concern yourself with path separator issues # Then there is the () parameter does not have to be a directory + filename form, no matter how many parameters can be stitched together # current_file_path = (current_file_dir, current_filename)
III. Some other operations on files and directories
3.1 Common operations on files
r -- Open the file in read mode and report an error if the file does not exist.
r+ - read/write mode opens the file and reports an error if the file does not exist. The original contents are not cleared when writing, but are overwritten by substitution.
w - Write mode opens the file and creates it if it does not exist. Existing contents are cleared.
w+ - read/write mode opens the file and creates it if it does not exist. Existing contents are cleared.
a - Append mode opens the file and creates it if it does not exist.
a+ - Read append mode opens the file and creates it if it does not exist.
import os file_name = "" new_file_name = "new_test.txt" # Blank documents created open(file_name, 'w').close() # Delete files (file_name) # Rename files (file_name, new_file_name) # Read the file with open(file_name, 'r') as fd: # Read everything () # Read a line () # Read all the rows and return a table of all the rows. () # Iterate through the rows of the file in a concise way for line in open(file_name, 'r', encoding='utf-8'): print(line) # Write files with open(file_name, 'w') as fd: # Write to file, need to add your own \n ("test_str") # Write to file, need to add your own \n The difference between # and write is that the arguments can be a list of strings, in addition to a string. (["test_str", "test_str"])
3.2 Common Operations of Catalogs
import os dir_name = "test_dir/dir_name" new_dir_name = "test_dir/new_dir_name" # Create the directory. This is the same as mkdir in the shell, and will fail if the parent directory does not exist. (dir_name) # Create a directory. This is similar to mkdir -p in the shell, which automatically creates a parent folder if it does not exist. (dir_name, exist_ok=True) # Delete the directory. This is the shell equivalent of rmdir, which fails if the directory is not empty. (dir_name) # Delete the directory. This is the shell equivalent of rm -rf. import shutil (dir_name) # Rename the directory. (dir_name, new_dir_name) # Traverse the catalog # dir_path is the current traversed directory. dir_names is the list of folders under dir_path. file_names is the list of files under dir_path. # If you want to whitelist directories, just remove the whitelisted directories from dir_names for (dir_path, dir_names, file_names) in (dir_name): for file_name in file_names: print((dir_path, file_name))
Above is how to get file path/directory of Python in detail, more information about Python to get file path/directory please pay attention to my other related articles!