• python 读取一个文件夹下的所jpg文件保存到txt中


    最近需要使用统计一个目录下的所有文件,使用python比较方便,就整理了一下代码。

     1 import os
     2 
     3 def gci(filepath):
     4     files = os.listdir(filepath)
     5     for fi in files:
     6         fi_d = os.path.join(filepath,fi)
     7         if os.path.isdir(fi_d):
     8             gci(fi_d)
     9         else:
    10             str = os.path.join(filepath,fi_d)+'
    ' 
    11             suffix = str[-5:]
    12             print(suffix)
    13             if(suffix == ".jpg
    "):
    14                 print(str ,'is a jpg file' + '
    ')
    15                 list_txt.writelines(str)
    16             else:
    17                 print(str,'is not a jpg file' + '
    ')
    18 
    19 
    20 # recursion traverse
    21 list_txt = open('list.txt', 'w')
    22 path = r'D:workerrorPic'
    23 print(path)
    24 gci(path)
    25 list_txt.close()

     在使用过程中发现使用记事本可以正常显示txt中的中文,使用notepad++查看时中文显示为乱码,解决办法:

    将上述代码中的一行改为下面一行:

    list_txt = open('list.txt', 'w', encoding='utf-8')

    也就是在开始写文件时就指定编码格式为utf-8.

  • 相关阅读:
    校验是否为日期格式
    校验是否为数字
    Python09函数基础、形参、实参
    Python05输入输出
    Python03序列操作
    Python10作用域、LEGB规则
    Python04运算符
    Python_08While循环
    Python07for循环
    Python09_01函数参数的传递
  • 原文地址:https://www.cnblogs.com/juluwangshier/p/11611498.html
Copyright © 2020-2023  润新知