如何在不同的目录下的不同机器上找到相同的文件夹?

2024-05-08 00:36:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我在目录/home/ubuntu/Desktop/Pythontraining中有两个名为StudentFaculty的文件夹。我需要在Student文件夹中保存10个文件,在Faculty文件夹中保存3个文件。在另一个系统中,如果StudentFaculty文件夹位于不同的目录中(例如:/home/documents/college),我也需要这样做。如何在不硬编码路径的情况下将文件存储到两台不同机器上的相应文件夹中?你知道吗


Tags: 文件路径目录文件夹编码homeubuntu系统
2条回答

对于这类问题,您有多种解决方案:

在每台机器上创建环境变量,在脚本中执行以下操作:

import os
student_path = os.environ['STUDENT_PATH']
faculty_path = os.environ['FACULTY_PATH']

print(student_path, faculty_path)

Personal opinion : I don't like to configure my scripts using environment variables as the ones you chose may be used by another software + it is always messy to debug


使用arguments

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("-s", " student")
parser.add_argument("-f", " faculty")

args = parser.parse_args()
student_path = args.student
faculty_path = args.faculty

print(student_path, faculty_path)

然后像这样调用脚本,并根据机器调整这行

python <yourscript> -s <student_path> -f <faculty_path>

Personal opinion : I use arguments when I want to control a small amount of parameters on my scripts to change its behavior (verbose, nb of cpus, ...).


创建配置文件并使用configparser

你知道吗配置.ini文件

[Paths]
student_path=<path_on_machine>
faculty_path=<path_on_machine>

脚本用法:

import configparser

config = configparser.ConfigParser()
config.read('config.ini')
student_path = config.get('Paths', 'student_path')
faculty_path = config.get('Paths', 'faculty_path')

print(student_path, faculty_path)

然后在每台机器上部署不同的config.ini文件(像ansible这样的工具可以帮助您实现自动化)

Personal opinion : I use config files when I need to adapt parameters when deploying on new machines. I don't like to use arguments for this purpose as I don't want to specify the same values every time I use my script (often these kind of parameters don't have good default values).


创建模块

您还可以创建一个模块来存储这些参数,而不是一个配置文件。你知道吗

我的_配置.py你知道吗

student_path="<path_on_machine>"
faculty_path="<path_on_machine>"

然后导入

你知道吗脚本.py你知道吗

import my_config

print(my_config.student_path, my_config.faculty_path)

I don't have any personal opinion on config files vs config modules. Read this if you want some elements of comparison.

可以使用walk库查找目标文件夹路径。如果每个搜索名称只有一个文件夹,则效果最佳:

import os

start = "/home/"

for dirpath, dirnames, filenames in os.walk(start):
    found = False
    for dirname in dirnames:
        if dirname == 'Student':
            full_path = os.path.join(dirpath, dirname)
            found = True
            break
    if found:
        break

输出:

/home/../学生

相关问题 更多 >