Python 打印指定目录下指定格式的文件列表

先直接贴代码

import sys
import os

def print_file_name(file_dir, file_format = "None"):   
  if (file_format == "None"): 
      for root, dirs, files in os.walk(file_dir):  
          for ele in files: 
              print(ele)
          break
  else:
      for root, dirs, files in os.walk(file_dir):  
          for ele in files: 
              temp_format = os.path.splitext(ele)[1]
              if (temp_format.lstrip(".") == file_format.strip().lstrip(".")): 
                  print(ele)
          break

params_ = sys.argv
lens_ = len(params_)

if lens_ > 3:
  print("Error: too many params.")
else: 
  if (lens_ == 1):
      abs_path = os.path.split(os.path.abspath(__file__))
      print_file_name(abs_path[0])
      sys.exit()
  elif(lens_ == 2):
       cur_format = params_[1]
       abs_path = os.path.split(os.path.abspath(__file__))
       print_file_name(abs_path[0], cur_format)
       sys.exit()
  else:
      cur_path = params_[2]
      cur_format = params_[1]
      print_file_name(cur_path, cur_format)

调用方式

  1. 先将上述代码保存成.py文件,比如保存成print_file_name.py
  2. 在命令行调用
  • 打印当前目录所有文件列表


  • 打印当前目录的所有指定格式的文件列表


  • 打印指定目录的指定格式的文件列表


©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Python 面向对象Python从设计之初就已经是一门面向对象的语言,正因为如此,在Python中创建一个类和对...
    顺毛阅读 4,250评论 4 16
  • ¥开启¥ 【iAPP实现进入界面执行逐一显】 〖2017-08-25 15:22:14〗 《//首先开一个线程,因...
    小菜c阅读 6,571评论 0 17
  • linux资料总章2.1 1.0写的不好抱歉 但是2.0已经改了很多 但是错误还是无法避免 以后资料会慢慢更新 大...
    数据革命阅读 12,240评论 2 33
  • 沉沉的夜里 看到醉酒的汉子 我怕,怕有一天 自己也变得和他一般 侧眼看自己的身姿 夜里,永远是孤弱弱的 像能被风吹...
    莫怨东风阅读 330评论 17 9
  • 当我们再一次来到操场看到今天上午金上阳光铺下的操场,那是一个让梦想留在心底,并付储行动努力实现的地方,当我们又...
    militarism阅读 752评论 6 1