如何根据正在使用的文件夹更改文件路径?

How to change file path according to folder in use?

我试图让这段代码中的in_features路径每次我运行程序都不一样,我已经处理了os.listdir ("./ content"),没有好的结果,就是什么我需要的是in_features每次我运行程序根据使用的文件夹改变,例如我可以select文件因为路径改变

import arcpy
import openpyxl as px

def main():
    wb = px.load_workbook(r"C:\Users\Hp\Desktop\Ejemplo\VINCULACION_S.xlsm", read_only=False, keep_vba=True)
    ws = wb['VINCULACION_SH_NUE']
    in_features = r"C:\Users\Hp\Desktop\Ejemplo\VH_Dissolve.shp"

    row_num = 3
    with arcpy.da.SearchCursor(
        in_features,
        ["COLOR", "INTERNO_DE", "CLASE_DEMA", "COUNT_AREA", "SUM_AREA", "SUM_LENGTH"],
    ) as cursor:
        for row in cursor:
            ws.cell(row=row_num, column=2).value = row[0]
            row_num += 1
    wb.save(r"C:\Users\Hp\Desktop\Ejemplo\VINCULACION_S.xlsm")

if __name__ == "__main__":
    main()

为了动态获取脚本当前所在目录的路径运行,您可以试试这个:

from pathlib import Path

in_feature = str(Path(__file__).parent / Path("VH_Dissolve.shp"))

因此,如果您的脚本是来自“C:\Users\NewDir\Ejemplo”的 运行,in_feature 的值将自动为 C:\Users\NewDir\Ejemplo\VH_Dissolve.shp