我有一个名为 ABC 的文件夹,其中有很多扩展名为 001.py、001.xls、001.pdf 等的文件。我想编写一个程序,在其中我们获取具有该文件名的列表 ["C:\Users\Desktop\ABC\001.py", "C:\Users\Desktop\ABC\001.xls", "C:\Users\Desktop\ABC\001.pdf"]我的代码:import osfrom os import listdirfrom os.path import isfile, joindir_path = os.path.dirname(os.path.realpath(__file__))print(dir_path) #current pathcwd = os.getcwd()list3 = []onlyfiles = [f for f in listdir(cwd) if isfile(join(cwd, f))]for i in onlyfiles: list3.append(dir_path+"\\"+i)print(list3) 我得到的输出为:["C:\\Users\\Desktop\\ABC\\001.py", "C:\\Users\\Desktop\\ABC\\001.xls", "C:\\Users\\Desktop\\ABC\\001.pdf"]我正在寻找输出:["C:\Users\Desktop\ABC\001.py", "C:\Users\Desktop\ABC\001.xls", "C:\Users\Desktop\ABC\001.pdf"]
1 回答
![?](http://img1.sycdn.imooc.com/54584f8f00019fc002200220-100-100.jpg)
一只名叫tom的猫
TA贡献1906条经验 获得超3个赞
如果你会使用Python 3,pathlib
可以帮助你以更清晰的方式组装你的路径!如果您被迫使用 Python 2,您可以引入它所基于的库!
双反斜杠之所以出现并需要处理,是因为 Windows 奇怪地选择使用\
而不是/
作为路径分隔符,而它在许多语言(尤其是 C 派生语言)中作为转义字符无处不在。您可以使用/
并且仍然可以正常工作。\
您会发现在不使用时也需要转义空格pathlib
。
添加回答
举报
0/150
提交
取消