python os.path.isfile 的使用誤區(qū)詳解
下列這幾條語句,看出什么問題了不?
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)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
- 三分鐘熟練使用Python的os.path.join()
- python中的os.path.join使用方法詳解
- Python中os.path.join函數(shù)的用法示例詳解
- python中os.path.exits()的坑
- python中join與os.path.join()函數(shù)實例詳解
- python中os.path.join()函數(shù)實例用法
- python中的split()函數(shù)和os.path.split()函數(shù)使用詳解
- 如何使用python3獲取當(dāng)前路徑及os.path.dirname的使用
- python os.path.isfile()因參數(shù)問題判斷錯誤的解決
- python中os.stat().st_size、os.path.getsize()獲取文件大小
相關(guān)文章
基于Python實現(xiàn)音樂節(jié)奏可視化效果
這篇文章主要為大家詳細(xì)介紹了如何基于Python語言實現(xiàn)音樂節(jié)奏可視化效果,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-06-06
pycharm通過ssh連接遠(yuǎn)程服務(wù)器教程
今天小編就為大家分享一篇pycharm通過ssh連接遠(yuǎn)程服務(wù)器教程,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02
如何實現(xiàn)在遠(yuǎn)程linux服務(wù)器上運行python代碼
這篇文章主要介紹了如何實現(xiàn)在遠(yuǎn)程linux服務(wù)器上運行python代碼問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-12-12

