溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

python os.path.isfile 的使用誤區(qū)詳解

發(fā)布時間:2020-08-25 21:56:33 來源:腳本之家 閱讀:119 作者:Deen12520 欄目:開發(fā)技術(shù)

下列這幾條語句,看出什么問題了不?

for file in os.listdir(path):
    if os.path.isfile(file) and os.path.splitext(file)[1] == '.txt':
      #打開txt文件,并提取數(shù)據(jù)

冥思苦想,沒錯啊,為啥 os.path.isfile(file)返回的就是false呢。

>>> os.listdir(path)
['cg.A.1.txt', 'cg.A.128.txt', 'cg.A.16.txt', 'cg.A.2.txt', 'cg.A.256.txt', 'cg.
A.32.txt', 'cg.A.4.txt', 'cg.A.512.txt', 'cg.A.64.txt', 'cg.A.8.txt', 'cg.B.1.tx
t', 'cg.B.128.txt', 'cg.B.16.txt', 'cg.B.2.txt', 'cg.B.256.txt', 'cg.B.32.txt',
'cg.B.4.txt', 'cg.B.512.txt', 'cg.B.64.txt', 'cg.B.8.txt', 'cg.C.1.txt', 'cg.C.1
28.txt', 'cg.C.16.txt', 'cg.C.2.txt', 'cg.C.256.txt', 'cg.C.32.txt', 'cg.C.4.txt
', 'cg.C.512.txt', 'cg.C.64.txt', 'cg.C.8.txt', 'cg.D.128.txt', 'cg.D.16.txt', '
cg.D.256.txt', 'cg.D.32.txt', 'cg.D.512.txt', 'cg.D.64.txt']
>>> files = os.listdir(path)
>>> os.path.isfile(files[1])
False

試驗了多次,仍然是False, 我去,什么鬼.....

開始Google,看到一些目錄操作,無果....

遂查看python自帶幫助,終于找到了答案,淚奔....

os.path.isfile(path)
Return True if path is an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same path.

注意:path是路徑.....

而我傳的是一個文件名.

解決方法就是:

>>> os.path.isfile(os.path.join(path,files[1]))
True

搞定!

以上這篇python os.path.isfile 的使用誤區(qū)詳解就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持億速云。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI