zoukankan      html  css  js  c++  java
  • 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)
  • 相关阅读:
    七, 表查询 一
    六, 表管理 二
    五,表管理 一
    四, 用户管理 二
    三, 用户管理 一
    二, 连接Oracle 二
    一,连接Oracle 一
    Oracle 11g 精简客户端
    解决Oracle在命令行下无法使用del等键问题
    NGINX反向代理,后端服务器获取真实IP
  • 原文地址:https://www.cnblogs.com/pingh/p/3439255.html
Copyright © 2011-2022 走看看