如何获取当前用户和脚本';python中的工作目录是什么?
目前,我正在使用以下代码段为脚本的源数据静态指定文件路径:如何获取当前用户和脚本';python中的工作目录是什么?,python,linux,windows,Python,Linux,Windows,目前,我正在使用以下代码段为脚本的源数据静态指定文件路径: def get_files(): global thedir thedir = 'C:\\Users\\username\\Documents' list = os.listdir(thedir) for i in list: if i.endswith('.txt'): print("\n\n"+i) eat_file(th
def get_files():
global thedir
thedir = 'C:\\Users\\username\\Documents'
list = os.listdir(thedir)
for i in list:
if i.endswith('.txt'):
print("\n\n"+i)
eat_file(thedir+'\\'+i)
我静态分配位置的原因是脚本在调试环境(如Eclipse和Visual Studio代码)中执行时无法正确执行。这些调试器假定脚本是从其工作目录运行的
由于我无法修改可能运行此脚本的每个系统的本地设置,是否有推荐的模块强制脚本获取活动用户(linux和windows)和/或脚本的本地目录 新的ish(在Python>=3.4中提供)非常适合处理类似路径的对象(包括Windows和其他操作系统)。使用它。不要为过时的os
模块操心。也不用费心尝试使用裸字符串来表示类似路径的对象
为了简化:您可以将任何路径(目录和文件路径对象被视为完全相同)构建为对象,可以是绝对路径对象或相对路径对象
简单显示一些有用的路径(如当前工作目录和用户主页)的工作原理如下:
from pathlib import Path
# Current directory (relative):
cwd = Path() # or Path('.')
print(cwd)
# Current directory (absolute):
cwd = Path.cwd()
print(cwd)
# User home directory:
home = Path.home()
print(home)
# Something inside the current directory
file_path = Path('some_file.txt') # relative path; or
file_path = Path()/'some_file.txt' # also relative path
file_path = Path().resolve()/Path('some_file.txt') # absolute path
print(file_path)
Path().mkdir('new/dir') # get errors if Path()/`new` doesn't exist
Path().mkdir('new/dir', parents=True) # will make Path()/`new` if it doesn't exist
Path().mkdir('new/dir', exist_ok=True) # errors ignored if `dir` already exists
要向下导航文件树,可以执行以下操作。请注意,第一个对象,home
,是一个路径
,其余只是字符串:
file_path = home/'Documents'/'project'/'data.txt' # or
file_path = home.join('Documents', 'project', 'data.txt')
要读取路径上的文件,可以使用其open
方法,而不是open
功能:
with file_path.open() as f:
dostuff(f)
但是你也可以直接抓取文本
contents = file_path.read_text()
content_lines = contents.split('\n')
…并直接编写文本
data = '\n'.join(content_lines)
file_path.write_text(data) # overwrites existing file
通过以下方式检查它是文件还是目录(并且存在):
file_path.is_dir() # False
file_path.is_file() # True
创建一个新的空文件,但不要像这样打开它(以静默方式替换任何现有文件):
要仅在文件不存在时创建该文件,请使用exist\u ok=False
:
try:
file_path.touch(exist_ok=False)
except FileExistsError:
# file exists
创建一个新目录(在当前目录下,Path()
),如下所示:
from pathlib import Path
# Current directory (relative):
cwd = Path() # or Path('.')
print(cwd)
# Current directory (absolute):
cwd = Path.cwd()
print(cwd)
# User home directory:
home = Path.home()
print(home)
# Something inside the current directory
file_path = Path('some_file.txt') # relative path; or
file_path = Path()/'some_file.txt' # also relative path
file_path = Path().resolve()/Path('some_file.txt') # absolute path
print(file_path)
Path().mkdir('new/dir') # get errors if Path()/`new` doesn't exist
Path().mkdir('new/dir', parents=True) # will make Path()/`new` if it doesn't exist
Path().mkdir('new/dir', exist_ok=True) # errors ignored if `dir` already exists
通过以下方式获取路径的文件扩展名或文件名:
file_path.suffix # empty string if no extension
file_path.stem # note: works on directories too
对路径的整个最后一部分使用name
(如果存在茎和延伸部分):
使用with_name
方法重命名文件(该方法返回相同的路径对象,但使用新文件名):
您可以使用iterdir
,像这样遍历目录中的所有“东西”:
all_the_things = list(Path().iterdir()) # returns a list of Path objects
您可以使用
os.getcwd()
获取当前工作目录。至于主目录,请参见os.path.expanduser()
脚本路径是主模块的\uuuu文件,或者对于冻结的可执行文件,sys.argv[0]
。路径可能与启动工作目录相关,因此您必须在修改工作目录之前立即捕获它。例如,script\u dir=os.path.abspath(os.path.dirname(sys.argv[0])
。
all_the_things = list(Path().iterdir()) # returns a list of Path objects