Discuss / Python / 求高手解释啊, 服了

求高手解释啊, 服了

Topic source

Tiiiso

#1 Created at ... [Delete] [Delete and Lock User]

import os

for x in os.listdir('C:/Users/ad/desktop/abc'): if os.path.isfile(x): print(x,'是文件') elif os.path.isdir(x): print(x,'是文件夹') else: print(x,'??')

运行结果: ab.txt ?? abc.txt ?? ac.txt 是文件 awer ?? bc.txt 是文件 eee ??


ab.txt abc.txt 明明是文本文件, 却判断不出来,
awer , eee 是文件夹, 也判断不出来, ac.txt, bc.txt 却正常, 服气了....

cc陈关谷

#2 Created at ... [Delete] [Delete and Lock User]

win10环境,测试没问题。 可能ab.txt abc.txt并不是文本文件, awer , eee并不是文件夹。

###代码 import os

for x in os.listdir('C:/Users/dell/Desktop/abc'): if os.path.isfile(x): print(x,'是文件') elif os.path.isdir(x): print(x,'是文件夹') else: print(x,'???')

###结果 ab.txt 是文件 abc.txt 是文件 ac.txt 是文件 awer 是文件夹 bc.txt 是文件 eee 是文件夹

Tiiiso

#3 Created at ... [Delete] [Delete and Lock User]

我是win7 , 不行, 百度了一下, 知道问题了 os.path.isdir() 如果传绝对路径, 就是对的, 如果传相对路径x 就不行 判断之前 加个 os.path.join(path,x) 就正常了

但是这也解释不了 为什么 有部分文件能正常判断....

廖雪峰

#4 Created at ... [Delete] [Delete and Lock User]

部分文件能正常判断是因为这些文件恰好在当前工作目录下

总是使用绝对路径判断

import os

def FindDir(file, prefix=os.path.abspath('.')): if len(os.listdir(prefix)) == 0: return for s in os.listdir(prefix): if os.path.splitext(s)[1] == '': FindDir(file, prefix + '\\' + s) elif s.find(file) != -1: print(prefix)

FindDir('123.txt')

输出: D:\Documents\Python\.idea\inspectionProfiles D:\Documents\Python


  • 1

Reply