Python 批量处理txt文本(保留数字)

import os

def readFile(filepath):
    f1 = open (filepath,"r")
    nowDir = os.path.split(filepath)[0]
    fileName = os.path.split(filepath)[1]
    newFileDir = os.path.join(nowDir, "python"+fileName)

    fnew = open(newFileDir,"w")

    content = f1.read()
    #s = [i for i in content if (str.isdigit(i) or i == '.' or i == '\n')] 等价于
    s = [] #s是个字符list
    for i in content:
    	#保留数字,小数点、空格与换行符
    	if (str.isdigit(i) or i == '.' or i == '\n' or i == ‘ ’): 
    		s.append(i)
    	#将冒号换空格
    	elif i == ':':
    		s.append(' ')
    s2 = ''.join(s)
    fnew.write(s2)
    
    f1.close()
    fnew.close()

def eachFile(filepath):
    pathDir = os.listdir(filepath)
    for s in pathDir:
        newDir = os.path.join(filepath,s)
        if os.path.isfile(newDir) :
            if os.path.splitext(newDir)[1] == ".txt":
                readFile(newDir)
                pass
        else:
            eachFile(newDir)

eachFile ('E:\\text')
print ("End!")

由https://www.cnblogs.com/SeekHit/p/6245283.html改的。

你可能感兴趣的:(Python)