【问题标题】:How can you harvest the current user and script's working directory in python?如何在 python 中获取当前用户和脚本的工作目录?
【发布时间】:2017-06-14 00:11:34
【问题描述】:

目前,我正在使用下面的 sn-p 为脚本的源数据静态指定文件路径:

 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 Code 等调试环境中执行时无法正确执行。这些调试器假定脚本是从它们的工作目录运行的。

由于我无法修改可能正在运行此脚本的每个系统的本地设置,是否有推荐的模块来强制脚本获取活动用户(linux 和 windows)和/或脚本的本地目录务实?

【问题讨论】:

  • 您可以通过os.getcwd()获取当前工作目录。至于主目录,见os.path.expanduser()
  • 脚本路径要么是主模块的__file__,要么是冻结的可执行文件sys.argv[0]。该路径可能与启动工作目录相关,因此您必须在修改工作目录之前立即捕获它。例如,script_dir = os.path.abspath(os.path.dirname(sys.argv[0]))。

标签: python linux windows


【解决方案1】:

新的pathlib module(在 Python >= 3.4 中可用)非常适合处理类似路径的对象(Windows 和其他操作系统)。用它。不要为过时的os 模块而烦恼。并且不要费心尝试使用裸字符串来表示类似路径的对象。

It's Paths - Paths all the way down

为了简化:您可以将任何路径(目录和文件路径对象被视为完全相同)构建为对象,可以是绝对路径对象或相对路径对象。

一些有用的路径的简单显示-例如当前工作目录和用户主目录-如下所示:

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)

要向下导航文件树,您可以执行以下操作。请注意,第一个对象 home 是 Path,其余的只是字符串:

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

创建一个新的空文件,不要像这样打开它(默默地替换任何现有文件):

file_path.touch()

要使文件仅在文件不存在时,请使用exist_ok=False:

try:
    file_path.touch(exist_ok=False)
except FileExistsError:
    # file exists

像这样创建一个新目录(在当前目录下,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 用于路径的整个最后部分(如果存在的话,则使用词干和扩展名):

file_path.name # note: works on directories too

使用with_name 方法重命名文件(该方法返回相同的路径对象但具有新的文件名):

new_path = file_path.with_name('data.txt')

您可以像这样使用iterdir 遍历目录中的所有“东西”:

all_the_things = list(Path().iterdir()) # returns a list of Path objects

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-25
    • 1970-01-01
    • 2011-01-07
    • 1970-01-01
    • 1970-01-01
    • 2021-12-02
    • 2011-06-19
    相关资源
    最近更新 更多