python提取文件中特定字符串

目录

1. Python3文件操作

1.1 打开和关闭文件

1.1.1 open( ) 函数

1.1.2 close( ) 函数

1.2  读写文件

1.2.1 write( ) 函数

1.2.2 read( ) 函数

2. 提取文件中特定字符串

代码如下(示例):



1. Python3文件操作

1.1 打开和关闭文件

1.1.1 open( ) 函数

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

参数说明:

    file: 必需,文件路径(相对或者绝对路径)。
    mode: 可选,文件打开模式
    buffering: 设置缓冲
    encoding: 一般使用utf8
    errors: 报错级别
    newline: 区分换行符
    closefd: 传入的file参数类型
    opener: 设置自定义开启器,开启器的返回值必须是一个打开的文件描述符。

1.1.2 close( ) 函数

#语法 无参数 没有返回值
fileObject.close();

 注意:使用 open() 方法一定要保证关闭文件对象,即调用 close() 方法。open() 函数常用形式是接收两个参数:文件名(file)和模式(mode)。

1.2  读写文件

1.2.1 write( ) 函数

fileObject.write( [ str ])

参数
    str -- 要写入文件的字符串。

1.2.2 read( ) 函数

fileObject.read([size]); 

参数
    size -- 从文件中读取的字符数(文本模式)或字节数(二进制模式),默认为 -1,表示读取整个文件。

2. 提取文件中特定字符串

代码如下(示例):

path = "C:/.../....txt"
str1 = ": Acc "
str2 = ", Best"

file = open(path, "r+")
count = len(open(path, 'r+').readlines())
print(count)
for line in range(0, count):
    with open(path) as f:
        data = f.readlines()[line]
        # print(data[data.index(str1)+6:])
        print(data[data.index(str1)+6: data.index(str2)])

file.close()

物联沃分享整理
物联沃-IOTWORD物联网 » python提取文件中特定字符串

发表评论