python笔记五 查询修改功能

import os

def fetch(data):  # 查询功能函数

    ret = ''  # 查询结果的返回列表

    tag = False

    with open('沪市股票', 'r') as hu_stock:

        for read_line in hu_stock:

            # print(read_line)

            if data in read_line[0:6]:  # 判断是否匹配输入号码

                tag = True

                print(read_line)

                ret = read_line

                continue

            if read_line.startswith('60') and tag:  # 判断结束条件

                break

            # if tag:

            #    print(read_line)

            #    ret.append(read_line)

            # elif data not in hu_stock:  # 查询无记录

            #    print('查询无记录。')

    return ret

def add(data):  # 修改功能函数

    res = fetch(data)

    def change(res):

        change_w = input('请输入替换内容:') #替换内容

        change_w = change_w + '\n' #添加内容的换行

        # print(change_w)

        with open('沪市股票', 'r') as hu_stock, open('沪市股票-new', 'w')as new_stock:

            for read_line in hu_stock:

                tag = False

                if read_line == res: #判断查询内容

                    tag = True

                    new_stock.write(change_w) #把替换内容写入

                if read_line.startswith('60') and tag:

                    tag = False

                    continue

                if not tag:

                    new_stock.write(read_line) #正常逐行写入文件

        os.rename('沪市股票','沪市股票.bak') #把原文件改为备份

        os.rename('沪市股票-new','沪市股票') #把新文件改成原文件

        # os.remove('沪市股票.bak')

        return new_stock

    return change(res)

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • mean to add the formatted="false" attribute?.[ 46% 47325/...
    ProZoom阅读 2,724评论 0 3
  • 1. Python的hello-world: print ("Hello, Python!")、 完了 摇就完事儿...
    LunarShade阅读 1,504评论 0 0
  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,448评论 0 10
  • 学习新东西当要用到我们的3W方法了(what why how),下面我们来学习下ros的api, 地址:https...
    追寻823阅读 9,894评论 0 0
  • A:三天假最后一天,准备给自己放一晚上假。 M:有些纠结,既想要好好休息,又想沉迷游戏。 B:调整状态。 R:恢复...
    有只熊爱冬眠阅读 69评论 0 0