Search code examples
pythonexcelopenpyxlarcpy

How to change file path according to folder in use?


I am trying to make the in_features path in this code different every time I run the program, I have dealt with os.listdir ("./ content"), without good results, that is, what I need is that in_features every time I I run the program change according to the folder of use, for example, that I can select the file since the path changes.

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()

Solution

  • In order to get dynamically the path of the directory where your script is currently run, you could try this:

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

    So, if your script was to be run from "C:\Users\NewDir\Ejemplo", the value of in_feature would automatically be C:\Users\NewDir\Ejemplo\VH_Dissolve.shp