美文网首页
Python 打印指定目录下指定格式的文件列表

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

作者: 小竹馆 | 来源:发表于2018-04-05 13:48 被阅读0次

先直接贴代码

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 打印指定目录下指定格式的文件列表

      本文链接:https://www.haomeiwen.com/subject/igorhftx.html