Find current directory and file's directory [d

2018-12-31 08:02发布

In Python, what commands can I use to find:

  1. the current directory (where I was in the terminal when I ran the Python script), and
  2. where the file I am executing is?

15条回答
笑指拈花
2楼-- · 2018-12-31 08:33

For question 1 use os.getcwd() # get working dir and os.chdir(r'D:\Steam\steamapps\common') # set working dir


I recommend using sys.argv[0] for question 2 because sys.argv is immutable and therefore always returns the current file (module object path) and not affected by os.chdir(). Also you can do like this:

import os
this_py_file = os.path.realpath(__file__)

# vvv Below comes your code vvv #

but that snippet and sys.argv[0] will not work or will work wierd when compiled by PyInstaller because magic properties are not set in __main__ level and sys.argv[0] is the way your exe was called (means that it becomes affected by the working dir).

查看更多
呛了眼睛熬了心
3楼-- · 2018-12-31 08:36

To Get your working directory in python. You can Use following code:

import os
cwd = os.getcwd() #to get current working directory
print(cwd)
查看更多
无色无味的生活
4楼-- · 2018-12-31 08:38

A bit late to the party, but I think the most succinct way to find just the name of your current execution context would be

current_folder_path, current_folder_name = os.path.split(os.getcwd())
查看更多
高级女魔头
5楼-- · 2018-12-31 08:39

In order to see current working directory type following script:

import os
current_working_directory = os.getcwd()
查看更多
不再属于我。
6楼-- · 2018-12-31 08:40

You may find this useful as a reference:

import os

print("Path at terminal when executing this file")
print(os.getcwd() + "\n")

print("This file path, relative to os.getcwd()")
print(__file__ + "\n")

print("This file full path (following symlinks)")
full_path = os.path.realpath(__file__)
print(full_path + "\n")

print("This file directory and name")
path, filename = os.path.split(full_path)
print(path + ' --> ' + filename + "\n")

print("This file directory only")
print(os.path.dirname(full_path))
查看更多
倾城一夜雪
7楼-- · 2018-12-31 08:40

If you're using Python 3.4, there is the brand new higher-level pathlib module which allows you to conveniently call pathlib.Path.cwd() to get a Path object representing your current working directory, along with many other new features.

More info on this new API can be found here.

查看更多
登录 后发表回答