• python学习三(数据保存到文件)


    以写模式打开文件:需要指定写模式,如下所示

    data = open('data.out','w')

    如果文件已经存在,则会清空它现有的所有内容。要追加一个文件,需要使用访问模式a,会追加到下一行。

    例子:将上节中Man和Other Man说的话,分别保存到两个文件中

    man = []
    other = []
    
    try:
        data = open('sketch.txt')
    
        for each_line in data:
            try:
                (role, line_spoken) = each_line.split(':')
                line_spoken = line_spoken.strip()
                if role == 'Man':
                    man.append(line_spoken)
                elif role == 'Other Man':
                    other.append(line_spoken)
                else:
                    pass
            except ValueError:
                pass
    
        data.close()
    except IOError:
        print('The datafile is missing!')
    #使用print将列表中的数据输出到文件中
    try:
        with open('man_data.txt', 'w') as man_file, open('other_data.txt', 'w') as other_file:
            print(man, file=man_file)
            print(other, file=other_file)
    except IOError as err:
        print('File error: ' + str(err))

    使用with open()方法保存文件,不需要再用close方法关闭文件

    Python提供了一个标准库,名为pickle,它可以加载、保存几乎任何的Python数据对象,包括列表

    使用python的dump保存,load恢复

    import pickle
    
    man = []
    other = []
    
    try:
        data = open('sketch.txt')
    
        for each_line in data:
            try:
                (role, line_spoken) = each_line.split(':')
                line_spoken = line_spoken.strip()
                if role == 'Man':
                    man.append(line_spoken)
                elif role == 'Other Man':
                    other.append(line_spoken)
                else:
                    pass
            except ValueError:
                pass
    
        data.close()
    except IOError:
        print('The datafile is missing!')
    
    try:
        with open('man_data.txt', 'wb') as man_file, open('other_data.txt', 'wb') as other_file:
            pickle.dump(man, file=man_file)
            pickle.dump(other, file=other_file)
    except IOError as err:
        print('File error: ' + str(err))
    except pickle.PickleError as perr:
        print('Pickling error: ' + str(perr))
        

    'wb'中的b表示以二进制模式打开文件

    要读取二进制文件使用'rb'

    import pickle
    with open('man_data.txt','rb') as readText:
        a_list = pickle.load(readText)
    print(a_list)
  • 相关阅读:
    稀疏自编码器一览表
    ZOJ 3886 Nico Number(筛素数+Love(线)Live(段)树)
    K好数(DP)
    【BZOJ4025】二分图
    又一次认识java(七) ---- final keyword
    二分查找
    从朴素贝叶斯分类器到贝叶斯网络(下)
    最近感到深深的绝望,感觉自己太菜了
    leetcode No.19 删除链表的倒数第N个节点 (python3实现)
    leetcode No.94 二叉树的中序遍历 (python3实现)
  • 原文地址:https://www.cnblogs.com/pingh/p/3439255.html
Copyright © 2020-2023  润新知