• 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)
  • 相关阅读:
    新年初六
    新年初五
    新年初四
    Who moved my cheese?
    红螺寺踏春
    JSP基本语法--实例演练
    JSP基础语法--跳转指令 jsp:forward page
    JSP基本语法--包含指令<%@include file="路径"%> <jsp:include page>
    JSP基本语法--Page指令 <%@page 属性=”内容“%>
    JSP注释及scriptlet <%局部%><%!全局%><%=输出%>
  • 原文地址:https://www.cnblogs.com/pingh/p/3439255.html
Copyright © 2020-2023  润新知