import os
import pandas as pd
# 要读取的文件目录
read_dir = './'
# 要保存的文件名
save_dir = './save.xlsx'
save_data = []
index = [
[2, 19, 26, 33, 50, 57],
[5, 20, 27, 36, 51, 58],
[8, 21, 28, 39, 52, 59],
[11, 22, 29, 42, 53, 60],
[14, 23, 30, 45, 54, 61]
]
for dir_path, dir_names, file_names in os.walk(read_dir):
for file_path in file_names:
if '.txt' not in file_path:
continue
print('当前', file_path)
with open(os.path.join(dir_path, file_path), 'r') as fp:
lines = fp.readlines()
lines = [line.strip() for line in lines]
# print(lines)
codes = []
for idx1 in index:
codes.append(lines[idx1[0] - 1].split()[0].split('_')[-1])
for idx1 in range(len(index)):
out_line = [file_path, lines[1].split('_')[0], codes[idx1]]
for idx2 in index[idx1]:
arr = lines[idx2 - 1].split()
if '缺陷' in arr[1] or '有裂纹' in arr[1]:
out_line.append(arr[2])
else:
out_line.append('')
# F1列
out_line.append('')
# F2列
out_line.append('')
print(out_line)
save_data.append(out_line)
columns = ['文件名', '日期', '编码', '上孔洞', '上分层', '上裂纹', '下孔洞', '下分层', '下裂纹', 'F1', 'F2']
df = pd.DataFrame(save_data, columns=columns)
df.to_excel(save_dir, index=None)
txt转excel-12345 固定行
于 2022-08-25 15:48:38 首次发布