简体   繁体   English

检查文件是Python 2.7.11中的目录还是常规文件

[英]Check if a file is a directory or a regular file in Python 2.7.11

I have written this code for checking if some of the files in a particular directory are further files or directories. 我已编写此代码来检查特定目录中的某些文件是否是其他文件或目录。

My file structure is like like: 我的文件结构就像:

C:\Users\Desktop\pythonprograms
|-temp1
|-temp2
|-sample.py

import os

filepath = os.getcwd()
backslash = "\\"
allfiles = os.listdir(filepath)

for indexval in range(filelist):
   print "File  ", indexval, allfiles[indexval], type(allfiles[indexval])   
checkfileisdir = filepath + backslash
dirsavailable = [checkfileisdir + indexval for indexval in allfiles]
for checkfile in dirsavailable:
    print os.path.isdir(checkfileisdir)

The above code returns True for the directories as well as the files. 上面的代码为目录和文件返回True。

Further, the following code does the trick of solving the problem. 此外,以下代码可解决问题。 I am looking for explanations rather than code snippets. 我在寻找解释而不是代码片段。

for indexval in range(filelist):
   print "File  ", indexval, allfiles[indexval], type(allfiles[indexval])           
   checkfileisdir = filepath + backslash + allfiles[indexval]
   print os.path.isdir(checkfileisdir),

I am not able to explain why. 我无法解释原因。 Can someone help me learn? 有人可以帮我学习吗?

Thanks in advance. 提前致谢。

You are trying to use incorrect function for your task. 您试图为您的任务使用不正确的功能。

Read in documentation 阅读文档

os.listdir os.listdir

Return a list containing the names of the entries in the directory given by path. 返回一个列表,其中包含由path给出的目录中条目的名称。 The list is in arbitrary order. 该列表是任意顺序的。 It does not include the special entries '.' 它不包括特殊条目“。” and '..' even if they are present in the directory. 和“ ..”,即使它们存在于目录中。

entries in the directory here is any kind of entry (file, directory, etc) 目录中的条目是任何类型的条目(文件,目录等)

You need to use this function: 您需要使用此功能:

os.walk(top, topdown=True, onerror=None, followlinks=False) os.walk(top,topdown = True,onerror = None,followlinks = False)

Generate the file names in a directory tree by walking the tree either top-down or bottom-up. 通过自上而下或自下而上移动目录树来生成文件名。 For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames). 对于以目录顶部(包括顶部本身)为根的树中的每个目录,它都会生成一个三元组(目录路径,目录名,文件名)。

Here is a good usage example 是一个很好的用法示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM