Python文本操作---数据筛选

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hiphopxiao/article/details/82629563

1.导入编码模块:codecs

2.open():方法打开文本

3.find():文本中找到相符和的值

4.write():写入文件

#字符串检索,
#find函数找到返回位置

import codecs  #编码
#第一个参数路径,第二个参数,rb二进制读写 第三个参数汉字编码,第四个参数忽略错误
file = codecs.open("D:\pythonText\info.txt","rb","gbk","ignore")
# 如果没有这个文件,新建一个文件,文件名为:q.txt
fileOpen = open("D:\pythonText\qq.txt", "w")

mystr = input("输入要查询的数据")
if __name__ == '__main__':
    while True:
        linestr=file.readline()#读取一行
        if linestr.find(mystr)!=-1:
            print(linestr) #显示数据
            # 写入这个文件
            fileOpen.write(linestr)
        if linestr== None: #读取失败返回值为None
            # 关闭这个文件
            fileOpen.close()
            break

猜你喜欢

转载自blog.csdn.net/hiphopxiao/article/details/82629563
今日推荐