摆脱glob.glob中的\\

问题描述

我有以下代码

ctypes.windll.user32.MessageBoxW(0,"Please choose a file directory","File directory",1)
EDS_database_path = filedialog.askdirectory()
EDS_answer = simpledialog.askstring("Input","Please enter the ID")

EDS_files_list = glob.glob(EDS_database_path+'/**'+EDS_answer+'**',recursive = True)

print(EDS_files_list)

输出中我得到:

['X:/data/Folder\\afilewithIDnumber.txt','X:/data/Folder\\anotherfilewithIDnumber.txt',]

因此该函数运行良好,但是我想摆脱“ \”并将其替换为“ /”,就像我在函数中明确想要做的那样。

解决方法

您可以使用print([filename.replace("\\","/") for filename in EDS_files_list])代替print(EDS_files_list)。这会将字符串中所有\\的实例替换为/,这将使其输出如您所愿。

,

您可以在python3中使用pathlib软件包,因为它是处理路径的新常识