# -*- coding: utf-8 -*-
"""
Created on Thu Aug 11 18:57:16 2022
"""
import os
import shutil
#重命名文件
pth = r'C:\test'
for folder in os.listdir(pth):
if os.path.isdir(os.path.join(pth,folder)):
subfolder = os.path.join(pth,folder)
if subfolder.split('\\')[-1] >= '20210101' and subfolder.split('\\')[-1]<= '20211231':
print(subfolder)
for file in os.listdir(subfolder):
if file == 'xxxxxxxxx' and len(file) == 9:
newname = file+folder+'.txt'
oldfile =os.path.join(subfolder,file)
newfile =os.path.join(subfolder,newname)
os.rename(oldfile,newfile)
#批量复制文件
pth = r'C:\test'
trgtfld = r'C:\result'
for folder in os.listdir(pth):
if os.path.isdir(os.path.join(pth,folder)):
subfolder = os.path.join(pth,folder)
if subfolder.split('\\')[-1] >= '20210101' and subfolder.split('\\')[-1]<= '20211231':
# print(subfolder)
for file in os.listdir(subfolder):
# print(file.split('.')[0][0:9])
if file.split('.')[0][0:9] =='xxxxxxxxx' and file.endswith('txt'):
shutil.copyfile(os.path.join(subfolder,file),os.path.join(trgtfld,file))
#重命名文件
import os
import shutil
def rename(pth):
for folder in os.listdir(pth):
if os.path.isdir(os.path.join(pth,folder)):
subfolder = os.path.join(pth,folder)
if subfolder.split('\\')[-1] >= '20210101' and subfolder.split('\\')[-1]<= '20211231':
print(subfolder)
for file in os.listdir(subfolder):
if file == 'xxxxxxxxx' and len(file) == 9:
newname = file+folder+'.txt'
oldfile =os.path.join(subfolder,file)
newfile =os.path.join(subfolder,newname)
os.rename(oldfile,newfile)
#批量复制文件
def copyfile(pth,trgpth):
rename(pth)
for folder in os.listdir(pth):
if os.path.isdir(os.path.join(pth,folder)):
subfolder = os.path.join(pth,folder)
if subfolder.split('\\')[-1] >= '20210101' and subfolder.split('\\')[-1]<= '20211231':
# print(subfolder)
for file in os.listdir(subfolder):
# print(file.split('.')[0][0:9])
if file.split('.')[0][0:9] =='xxxxxxxxx' and file.endswith('txt'):
shutil.copyfile(os.path.join(subfolder,file),os.path.join(trgtfld,file))
pth = r'C:\test'
trgpth = r'C:\result'
copyfile(pth,trgpth)
#批量合并文件
import pandas as pd
trgpth = r'C:\test'
#总行数计数
count2 = 0
for file in os.listdir(trgpth):
# print(file)
filename = os.path.join(trgpth,file)
# 读取
inputfile = open(filename, 'r',encoding = 'GB2312')
a = []
# 将数据进行格式化处理,获取dataframe类型数据
# 单个文件计数
count = 0
for line in inputfile:
# count+=1
# count2+=1
# print(line)
#剪切掉行前和行末的空格,若只想剪切行前,则用line.lstrip(),行末则用line.rstrip()
# count = 0
line = line.strip()
#分割,用split(),默认是按空格分割,无论是一个空格还是多个空格均可
wordlist = line.split()
if '成功' in wordlist:
# count2 = 0
count+=1
# print(wordlist)
#可以将字符串转化为浮点型数据
a.append(wordlist)
count2+=1
# print(count)
print(file,count)
print(count2)
names = ['x1', 'x2', 'x3', 'x4', 'x5', 'x6', 'x7', 'x8', 'x9'] #,'x10','x11','x12'
df = pd.DataFrame(columns=names, data=a)
# 修改格式后的源数据
pth = r'C:\test'
tofile = os.path.join(pth,'dataframe.csv')
df.to_csv(tofile,index = 0)
#print(a)