用python修改项目内空文件

因为公司的同步系统不允许空文件上传,而最近做的项目是用phpcms改的,所以当中有很多空的index.html或是index.htm,影响文件上传

所以决定用python写一个程序,可以让他递归目录下的所有文件,找出空的html文件写入部分数据。初学python写的这段东西只限于能用。。。。

# -*- coding:utf8 -*-
import os
filelist = []
file_num=0
def dp(path):
    sep=os.sep
    global file_num
    dirlist = []
    file_ext_list=('.html','.htm')
    files = os.listdir(path)

    for f in files:
        if os.path.isdir(path+sep+f):
            dp(path+sep+f)
        if os.path.isfile(path+sep+f):
            file_ex=os.path.splitext(path+sep+f)[1]
            
            if (os.path.getsize(path+sep+f) == 0 and file_ex in file_ext_list):
                fileHandle=open(path+sep+f,"w")
                try:
                    fileHandle.write("fadflkja")
                    file_num = file_num +1
                finally:
                    fileHandle.close()
                filelist.append(path+sep+f)
dp(r"F:\phpnow\htdocs\test")
print file_num

这里值得注意的地方是 open这个函数,他的参数是w的时候是相当于删除掉文件原有内容,如果是要在文件后追加,请用a这个参数

原文地址:https://www.cnblogs.com/youxu/p/3098602.html