2022年 11月 5日

python遍历文件

一、遍历文件夹下所有文件并打印文件名

import os

def main():
    #文件路径
    file_path = r'F:\test1022\学习资料'
    #提取文件中的所有文件生成一个列表
    folders = os.listdir(file_path)
    for file in folders:
        #打印所有文件名
        print(file)

if __name__ == '__main__':
    main()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

输出结果:

D:\ProgramFiles\python3.8\python.exe F:/test1022/ttt.py
9780470744635.ch1.pdf
base_main.xls
multi1_640x360_5qp_27.txt
好好学习.txt

Process finished with exit code 0
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

二、遍历文件夹下指定类型文件并打印文件名

import os

def main():
    #文件路径
    file_path = r'F:\test1022\学习资料'
    #提取文件中的所有文件生成一个列表
    folders = os.listdir(file_path)
    for file in folders:
        #判断文件后缀名是否为txt
        if(file.split('.')[-1]=='txt'):
            # 打印所有txt文件名
            print(file)

if __name__ == '__main__':
    main()
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

输出结果:

D:\ProgramFiles\python3.8\python.exe F:/test1022/ttt.py
multi1_640x360_5qp_27.txt
好好学习.txt

Process finished with exit code 0
  • 1
  • 2
  • 3
  • 4
  • 5