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语句,用于定义函数和类型的方法。

1.1 读取整个文件

要读取文件,需要一个包含几行文本的文件(文件PI_DESC.txt与file_reader.py在同一目录下)

PI_DESC.txt

3.1415926535

8979323846

2643383279

5028841971

file_reader.py

with open("PI_DESC.txt") as file_object:

contents = file_object.read()

print(contents)

我们可以看出,读取文件时,并没有使用colse()方法,那么未妥善的关闭文件,会不会导致文件收到损坏呢?在这里是不会的,因为我们在open()方法前边引入了关键字with,该关键字的作用是:在不需要访问文件后将其关闭

1.2文件路径

程序在读取文本文件的时候,如果不给定路径,那么它会先在当前目录下进行检索,有时候我们需要读取其他文件夹中的路径,例如:

现在文件PI_DESC.txt存储在python目录的子文件夹txt中

那么我们读取文本内容的代码得修改为:

with open("txt\PI_DESC.txt") as file_object:

contents = file_object.read()

print(contents)

给open参数传递的参数得给相对路径

在Windows中,使用反斜杠(\),但是由于python中,反斜杠被视为转义字符,在Windows最好在路径开头的单(双)引号前加上r

相对路径:即相对于程序文件的路径

绝对路径:即文本在硬盘上存储的路径

使用绝对路径的程序怎么写呢 ?

with open(r"D:\python\txt\PI_DESC.txt") as file_object:

contents = file_object.read()

print(contents)

1.3逐行读取

读取文件时,可能需要读取文件中的每一行,要以每一行的方式来检查文件或者修改文件,那么可以对文件对象使用for循环

file_path = 'txt\PI_DESC.txt'with open(file_path) as file_object:

for line in file_object:

print(line)

程序运行结果如下:

通过运行结果我们可以看出,打印结果中间有很多空白行,这些空白行是怎么来的呢?因为在这个文件中,每行的末尾都有一个看不见的换行符,而print语句也会加一个换行符,因此每行末尾就有2个换行符:一个来自文件,另外一个来自print,消除这些换行符,只需要使用方法rstrip()

file_path = 'txt\PI_DESC.txt'with open(file_path) as file_object:

for line in file_object:

print(line.rstrip())

打印结果

通过运行结果我们可以看出,打印结果中间有很多空白行,这些空白行是怎么来的呢?因为在这个文件中,每行的末尾都有一个看不见的换行符,而print语句也会加一个换行符,因此每行末尾就有2个换行符:一个来自文件,另外一个来自print,消除这些换行符,只需要使用方法rstrip()

file_path = 'txt\PI_DESC.txt'with open(file_path) as file_object:

for line in file_object:

print(line.rstrip())

打印结果

1.4创建一个包含文件各行内容的列表

使用关键字with时,open()返回的文件对象只能在with代码块可用,如果要在with代码块外访问文件的内容,可在with块中将文件各行存储在一个列表,并在with代码块外使用该列表

file_path = 'txt\PI_DESC.txt'with open(file_path) as file_object:

lines = file_object.readlines()for line in lines:

print(line.rstrip())

1.5使用文件的内容

在上面一节中我们提到把数据提取到内存中,那么我们就可以对数据进行随心所欲的 *** 作了

需要:将圆周率连在一起打印出来(删除空格),并打印其长度

file_path = 'txt\PI_DESC.txt'with open(file_path) as file_object:

lines = file_object.readlines()pi_str = ''for line in lines:

pi_str += line.strip()print(pi_str.rstrip())print(len(pi_str.rstrip()))

file_path = 'txt\PI_DESC.txt'with open(file_path) as file_object:

lines = file_object.readlines()pi_str = ''for line in lines:

pi_str += line.strip()print(pi_str.rstrip())print(len(pi_str.rstrip()))

注意最后print语句并没有缩进,如果是缩进的话就会每取一行打印一次

打印效果如下


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

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

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

发表评论

登录后才能评论

评论列表(0条)

保存