python如何读取文件的内容

python如何读取文件的内容,第1张

# _*_ 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]

1、Python

Python(英语发音:/ˈpaɪθən/), 是一种面向对象、解释型计算机程序设计语言,由Guido van Rossum于1989年底发明,第一个公开发行版发行于1991年,Python 源代码同样遵循 GPL(GNU General Public License)协议。

2、基本概念

Python(KK 英语发音:/'paɪθɑn/, DJ 英语发音:/ˈpaiθən/)是一种面向对象、直译式计算机程序设计语言,由Guido van Rossum于1989年底发明。


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/tougao/12082356.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-20
下一篇 2023-05-20

发表评论

登录后才能评论

评论列表(0条)

保存