代码编写如下,环境在windows10, python3.8, pip install configparser(注意在Pyhton3中configparser是小写)
import time
from tkinter import *
import tkinter.filedialog
import sys
import os
import configparser
def read_file(file_path):
with open(file_path, 'r') as f:
lines = f.readlines()
return lines
#config.ini configuration as follow:
#[test_section]
#test_p1 =14da,147,400
# find the configuration from config.ini
def find_id(configfile='config.ini'):
curpath = os.path.dirname(os.path.realpath(__file__))
cfgpath = os.path.join(curpath, configfile)
# print(cfgpath)
config = configparser.RawConfigParser()
config.read(cfgpath)
id_value = config.get("test_section", "test_p1")
# id_value=[14da,147,400]
id_list = id_value.split(',')
if id_list == '':
print('Config.ini is wrong.')
return id_list
def modifyTimeStamp(string_data, id_list=['14da']):
split_line = string_data.split(' ')
# It is a string for every line of data, get a List by using split(' ') a bracket
# print(split_line), the results as follow:
# ['', '', '', '0.006963', '', '8', '0147', '', '', '', '', '', '', '', '', '', '', '', 'Tx', '', '', 'd8', '00',
# '50', '80', '00', '00', '00', '00', '0F\n']
flag = 'false'
for data in split_line[3:]:
for matchedID in id_list:
# ID matched
if data == matchedID:
flag = 'true'
break
if flag == 'true':
break
if flag == 'false':
split_line = ''
return split_line
if __name__ == "__main__":
start_time = time.time()
# Start time of the program
root = Tk()
# Create a Tkinter.Tk() object
root.withdraw()
# Hide Tkinter.Tk() object
input_file = tkinter.filedialog.askopenfilename(title=u'Create a file')
# save the path to variable filenames
data_lines = read_file(input_file)
# Read .asc source data file
id_list = find_id(configfile='config.ini')
output_file = tkinter.filedialog.asksaveasfilename(title=u'save file')
# save the path to variable output_file
print('Read over. Total lines: %d' % len(data_lines))
with open(output_file, 'w') as fp:
for i in range(len(data_lines)):
if i > 2:
split_line = modifyTimeStamp(data_lines[i], id_list)
s2 = " ".join([e for e in split_line])
# Connect all of data to be a big string
# print(s2)
# The results shows as follow:
# 8.990842 1 380 Rx d8 03 00 51 00 39 00 00 00
fp.write(s2)
# write to file
else:
fp.write(data_lines[i]) # Do not change the first two lines of data in this file
print("--- Time cost %s seconds ---" % (time.time() - start_time))
# Record the executing time of this program
转载请注明原文地址:https://ipadbbs.8miu.com/read-25750.html