python os.path.isfile 的使用误区详解

yipeiwu_com6年前Python基础

下列这几条语句,看出什么问题了不?

for file in os.listdir(path):
    if os.path.isfile(file) and os.path.splitext(file)[1] == '.txt':
      #打开txt文件,并提取数据

冥思苦想,没错啊,为啥 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 的使用误区详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

nginx搭建基于python的web环境的实现步骤

nginx搭建基于python的web环境的实现步骤

前言: 在搭建开始前,我们先来梳理下web服务工作流程,先看下图: 1、用户(PC)向web服务器发起http请求 2、web服务器判断用户请求文件是否为静态文件,是则直接读取静态文件...

python Kmeans算法原理深入解析

python Kmeans算法原理深入解析

一. 概述 首先需要先介绍一下无监督学习,所谓无监督学习,就是训练样本中的标记信息是位置的,目标是通过对无标记训练样本的学习来揭示数据的内在性质以及规律。通俗得说,就是根据数据的一些内...

python安装twisted的问题解析

python安装twisted的问题解析

今天在用pip安装wisted模块的时候没有任何的问题,但是当使用的时候发生了,无法导入win32api这个包,原因是因为python不能自己去使用系统的api。因此需要去安装pywin...

Pycharm最新激活码2019(推荐)

Pycharm最新激活码2019(推荐)

pycharm2019激活码是专门针对与pycharm2019这一款软件而研发的激活码,能够完美激活软件,并且能够支持2019.1版本,理论上也能够支持后继的2019.2,2019.3,...

pygame实现俄罗斯方块游戏(基础篇2)

pygame实现俄罗斯方块游戏(基础篇2)

接上章《pygame实现俄罗斯方块游戏(基础篇1)》继续写俄罗斯方块游戏 五、计算方块之间的碰撞 在Panel类里增加函数 def check_overlap(self, diffx...