菜鸟教程 -- 学的不仅是技术,更是梦想!

Python 基础教程
(追記) (追記ここまで)

Python os.listdir() 方法

Python File(文件) 方法 Python OS 文件/目录方法


概述

os.listdir() 方法用于返回指定的文件夹包含的文件或文件夹的名字的列表。

它不包括 ... 即使它在文件夹中。

只支持在 Unix, Windows 下使用。

注意:针对目录下有中文目录对情况,Python2 需要经过编码处理,但是在 Python3 中不需要已经没有 unicode() 方法,默认是 utf8 编码,所以需要转。

语法

listdir()方法语法格式如下:

os.listdir(path)

参数

  • path -- 需要列出的目录路径

返回值

返回指定路径下的文件和文件夹列表。

实例

以下实例演示了 listdir() 方法的使用:

实例

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import os, sys

# 打开文件
path = "/var/www/html/"
dirs = os.listdir( path )

# 输出所有文件和文件夹
for file in dirs:
print (file)

执行以上程序输出结果为:

test.htm
stamp
faq.htm
_vti_txt
robots.txt
itemlisting
resumelisting
writing_effective_resume.htm
advertisebusiness.htm
papers
resume

Python2 版本针对目录中存在中文的情况,目录结构如下:

实例

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import os

# 打开文件
path = "./git-test"
upath = unicode(path,'utf-8')
dirs = os.listdir( upath )
# 输出所有文件和文件夹
for file in dirs:
print (file)

执行以上程序输出结果为:

runoob
runoob-git-test
another-runoob-name
中文目录测试

Python File(文件) 方法 Python OS 文件/目录方法

AI 思考中...

1 篇笔记 写笔记

  1. #0

    Tom

    mao***@163.com

    242

    如果目录下有中文目录,打印时遇到乱码解决方法:

    cPath = os.getcwd()
    # 如果目录名字为中文 需要转码处理
    uPath = unicode(cPath,'utf-8')
    for fileName in os.listdir(uPath) :
     print fileName

    Tom

    mao***@163.com

    8年前 (2019年01月05日)

点我分享笔记

  • 昵称 (必填)
  • 邮箱 (必填)
  • 引用地址

AltStyle によって変換されたページ (->オリジナル) /