Search code examples
python-3.xpathsubprocess

How to convert a '\' path to '\\'


I'm coding a software in python and I'm trying to convert a windows path with \ like C:\Program Files\KiCad\7.0\bin to a path with \\ C:\\Program Files\\KiCad\\7.0\\bin so that it will be recognized as a path by python in send in a subprocess. Run command.

I tried Path () from pathlib; OS. Path. Normpath () but it doesn't work...


Solution

  • Below function takes a path as parameter and prints all filenames with absolute path with double \\. It's pretty simple.

    def get_absolutePath_for_all_file(path):
        for filename in os.listdir(path):
            abs_path = os.path.join(path, filename)
            abs_path = abs_path.replace('\\','\\\\')
            print(abs_path)
    
    path = r'C:\Users\mdmsarke\Desktop\MS_Data\Developer\GES_Survey\FY_22_23'
    get_absolutePath_for_all_file(path)
    

    Output:

    C:\\Users\\mdmsarke\\Desktop\\MS_Data\\Developer\\GES_Survey\\FY_22_23\\future_contact_information
    C:\\Users\\mdmsarke\\Desktop\\MS_Data\\Developer\\GES_Survey\\FY_22_23\\ges_raw_data_choice_text_6_27_23.csv
    C:\\Users\\mdmsarke\\Desktop\\MS_Data\\Developer\\GES_Survey\\FY_22_23\\ges_raw_data_choice_text_6_27_23_for_upload.csv
    C:\\Users\\mdmsarke\\Desktop\\MS_Data\\Developer\\GES_Survey\\FY_22_23\\ges_raw_data_choice_text_fall_2022.csv
    C:\\Users\\mdmsarke\\Desktop\\MS_Data\\Developer\\GES_Survey\\FY_22_23\\ges_raw_data_choice_text_fall_2022_for_upload.csv
    C:\\Users\\mdmsarke\\Desktop\\MS_Data\\Developer\\GES_Survey\\FY_22_23\\ges_raw_data_numerical_6_27_23.csv