繁体   English   中英

您如何在python中收获当前用户和脚本的工作目录?

[英]How can you harvest the current user and script's working directory in python?

目前,我正在使用以下代码段为脚本的源数据静态指定文件路径:

 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)和/或脚本的本地目录?

全新的pathlib模块 (在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)

要浏览文件树,您可以执行以下操作。 请注意,第一个对象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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM