zoukankan      html  css  js  c++  java
  • 读取、写入文件 、存储数据

    一、读取文件

    1、读取整个文件

    file_name = 'cat.txt'

    with open(file_name) as file_object:

      contents = file_object.read()

     print(contents) 

    2、逐行读取,可使用for循环

    file_name = 'cat.txt'

    with open(file_name) as file_object:

      for line in file_object:

        print(line.rstrip())

    3、创建一个包含文件各行内容的列表

    file_name = 'cat.txt'

    with open(file_name) as file_object:

      lines = file_object.readlines()

    for line in lines:

      print(line.rstrip())

    4、使用文件的内容

    file_name ='pi.txt'

    with open(file_name) as file_object:

      lines = file_object.readlines()

    pi_string = ' '

    for line in lines:

      pi_string += line

    print(pi_string)

    二、写入文件

    1、‘w’写入

    with open(filename,'w') as file_object:

      file_object.write(I want to hide")

    注:写入多行时后面需要加换行符。

    2、‘a'附加  

    with open(filename,'a') as file_object:

      file_object.write('I want to sleep')

    三、异常

    try-except-else

    else在try代码块中执行成功时运行else代码块。

    四、存储数据

    1、json.dump() 接受两个实参,要存储的数据,以及要存储数据的文件类型

       json.load()接受一个实参,文件类型

    2、如何用json.dump()来存储列表

    import json

    numbers = [1,2,3,4,5,6]

    filename = number.josn

    with open(filename,'w') as file_object:

      josn.dump(numbers,file_object)

    3、保存和读取用户生成的数据

    import json
    file_name = 'number.json'
    try:
    with open(file_name) as file_object:
    fav_number = json.load(file_object)

    except:
    number = input("请输入你喜欢的数字:")
    with open(file_name,'w') as file_object:
    fav_number = json.dump(number,file_object)
    else:
    print("您最喜欢的数字是:%s" % fav_number)

    4、重构

    import json
    file_name = 'username.json'
    def got_name():
    """获取用户名称"""
    try:
    with open(file_name) as file_object:
    user_name = json.load(file_object)
    except:
    return None
    else:
    return user_name

    def new_name():
    """提醒用户输入名字"""
    user_name = input("请输入您的名字:")
    with open(file_name,'w') as file_object:
    put_name = json.dump(user_name,file_object)
    return user_name


    def greet():
    """向用户发出问候"""
    username = got_name()
    if username:
    ask = input("用户名是%s吗?"%username)
    if ask == 'y':
    print("欢迎回来%s"%username)
    else:
    user_name =new_name()
    print("下次我会记得你哦!%s"%user_name)
    else:
    user_name = new_name()
    print("下次我会记得你哦!%s" % user_name)
    greet()
    在任何时候去学习都不晚,永远不要放弃自己!人生就是一个不断去学习的过程,任何时候,只要你想学,Come on !
  • 相关阅读:
    sed替换
    【工作提升】好员工秘诀十二条
    【工作提升】怎么样做工作才有好的效果
    vim删除空行和注释
    Java实现几种常见排序方法
    数据背后的二八定律,揭示程序员担忧的主要问题
    【新闻】国内第一本介绍程序员996现象的技术图书上市,“再谈工作996,生病ICU”一文受关注
    10年磨一剑:《SOD框架“企业级”应用数据架构实战》一书正式上市
    程序员肺被切掉一块还得去加班... 再谈“工作996,生病ICU”
    win10编译pdfium
  • 原文地址:https://www.cnblogs.com/startingpoint-fly/p/10655922.html
Copyright © 2011-2022 走看看