python读取robot文件内容_python读取文件的内容并解析
一,python解析文件:1)读取文件存入内存2)然后根据字符串进行处理3)最后将数据转换成数组4)最后利用dataframe解析数据# _*_ coding: utf-8 _*_import pandas as pd# 获取文件的内容def get_contends(path):with open(path) as file_object:contends = file_object.read(
一,python解析文件:
1)读取文件存入内存
2)然后根据字符串进行处理
3)最后将数据转换成数组
4)最后利用dataframe解析数据
# _*_ coding: utf-8 _*_
import pandas as pd
# 获取文件的内容
def get_contends(path):
with open(path) as file_object:
contends = file_object.read()
return contends
# 将一行内容变成数组
def get_contends_arr(contends):
contends_arr_new = []
contends_arr = str(contends).split(']')
for i in range(len(contends_arr)):
if (contends_arr[i].__contains__('[')):
index = contends_arr[i].rfind('[')
temp_str = contends_arr[i][index + 1:]
if temp_str.__contains__('"'):
contends_arr_new.append(temp_str.replace('"', ''))
# print(index)
# print(contends_arr[i])
return contends_arr_new
if __name__ == '__main__':
path = 'event.txt'
contends = get_contends(path)
contends_arr = get_contends_arr(contends)
contents = []
for content in contends_arr:
contents.append(content.split(','))
df = pd.DataFrame(contents, columns=['shelf_code', 'robotid', 'event', 'time'])
print(df)
二,用json读取数组数据:
# _*_ coding: utf-8 _*_
import pandas as pd
import json
file = open("event.txt")
context = file.readline()
data = json.loads(context)
data = data['data']
pd.DataFrame(data, columns=['shelfCode', 'robotId', 'action', 'time'])
第二种方法比较简洁,更适合于生产环境
更多推荐
所有评论(0)