2022-01-13 23:52来源:m.sf1369.com作者:宇宇
# _*_ 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'])
扩展资料:
python控制语句
1、if语句,当条件成立时运行语句块。经常与else, elif(相当于else if) 配合使用。
2、for语句,遍历列表、字符串、字典、集合等迭代器,依次处理迭代器中的每个元素。
3、while语句,当条件为真时,循环运行语句块。
4、try语句,与except,finally配合使用处理在程序运行中出现的异常情况。
5、class语句,用于定义类型。
6、def语句,用于定义函数和类型的方法。
python读取文件内容的方法: 一.最方便的方法是一次性读取文件中的所有内容并放置到一个大字符串中: all_the_text = open('thefile.txt').read( ) # 文本文件中的所有文本 all_the_data = open('abinfile','rb').read( ) # 二进制文件中的所有数据 为了安全起见,最好还是给打开的文件对象指定一个名字,这样在完成操作之后可以迅速关闭文件,防止一些无用的文件对象占用内存。举个例子,对文本文件读取: file_object = open('thefile.txt') try: all_the_text = file_object.read( ) finally: file_object.close( ) 不一定要在这里用Try/finally语句,但是用了效果更好,因为它可以保证文件对象被关闭,即使在读取中发生了严重错误。 二.最简单、最快,也最具Python风格的方法是逐行读取文本文件内容,并将读取的数据放置到一个字符串列表中: list_of_all_the_lines = file_object.readlines( ) 这样读出的每行文本末尾都带有\n符号;如果你不想这样,还有另一个替代的办法,比如: list_of_all_the_lines = file_object.read( ).splitlines( ) list_of_all_the_lines = file_object.read( ).split('\n') list_of_all_the_lines = [L.rstrip('\n') for L in file_object] 最简单最快的逐行处理文本文件的方法是,用一个简单的for循环语句: for line in file_object: process line 这种方法同样会在每行末尾留下\n符号;可以在for循环的主体部分加一句: lineline = line.rstrip('\n') 或者,你想去除每行的末尾的空白符(不只是'\n'\),常见的办法是: lineline = line.rstrip( )