• Python 文件&异常 初学者笔记


    文件

     读取整个文件

    with open('pi_30_digits.txt') as file_object :#Python在当前执行文件目录寻找指定文件
    #filename = 文件的绝对路径或相对路径
    #with open(filename) as file_object : #open()打开文件;with在不再需要访问文件后将其关闭 contents = file_object.read()#读取文件内容为字符串类型; print(contents.rstrip())#read()读取到文件到结尾时会返回一个空字符

     逐行读取文件

    filename = 'pi_digits.txt'
    
    with open(filename) as file_object:
        for line in file_object:#使用for循环实现逐行读取
            print(line.rstrip())#别忘记每个print语句结束都会自动加上一个换行符哦
    

     使用文件内容

     使用with时ope()返回文件的对象仅在with代码块内可用,可使用方法readlines将其存储在一个列表中实现全局使用

    filename = 'pi_digits.txt'
    
    with open(filename) as file_object:
        lines = file_object.readlines()#方法readlines()从文件中读取每一行,并将其存储在一个列表中
    pi_string = ''#一个空字符用于储存圆周率
    for line in lines:
        pi_string += line.strip()#使用for循环组成圆周率
    print(pi_string)
    print(len(pi_string))
    #print(pi_string[:52] + '...')切片打印,多用于大型文件,不易全部查看
    float(pi_string)

     替换文件中的内容

    file_name = 'learning.txt'
    with open(file_name) as my_python:
        lines = my_python.readlines()
    py_string = ''
    for value in lines:
        py_string += value.replace('Python', 'JAVA')#替换内容
    print(py_string)
    

     写入文件

    rwar+ 在py中分别为:读、写、附加、可读可写模式

    Python默认以只读模式打开文件,且Python只能将字符串写入文件;

    以附加模式打开文件时写入的内容都将添加到文件末尾;如指定文件不存在,Python将自动创建一个空文件

    filename = 'programming.txt'
    
    with open(filename, 'w') as  file_object:#实参w,即以写入模式打开这个文件
        file_object.write("I love programming")#函数write()写入文件时,不会在末尾添加换行符
    

    异常

    常见的异常对象:https://www.cnblogs.com/MR---Zhao/articles/12346749.html

    使用try-except处理异常,让用户不再疑惑traceback

    try:
        '''可能发生异常的代码放在此处'''
    except ZeroDivisionError:
        '''发生异常的解决方案代码放在此处'''
    else:
        '''try的代码成功执行后要执行的代码放在这里'''
    

    分析文本

    方法split()以空格为分隔符将字符分拆成多个部分,并储存到一个列表中

    def count_words(filename):
        '''定义一个函数出来多个文件'''
        try:
            with open(filename) as f_obj:
                contents = f_obj.read()
        except FileNotFoundError:
           pass#发生异常时“一声不吭”(不显示错误)
        else:
            words = contents.split()#以空格为分隔符将words中的内容分拆成多个部分,并储存到一个列表中
            num_words =len(words)#测试列表长度,即words中的单词数
            print("The file " + filename + " has about " + str(num_words) + " words." )
    '''创建列表循环实现处理大量文本功能'''
    filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt']
    for filename in filenames:
        count_words(filename)
    

     储存数据

    json.dump()  接受两个实参:要存储的数据以及可用于存储数据的文件对象

    import json#导入模块
    
    numbers =[2, 3, 5, 7, 11, 16]
    
    filename = 'numbers.json'
    with open(filename, 'w') as f_obj:
        json.dump(numbers, f_obj)#将前者储存到后者
    

    储存用户输入

    import json
    
    filename = 'username.json'
    username = input("你的名字: ")
    
    with open(filename, 'w') as f_obj:
        json.dump(username, f_obj)#储存用户输入
        print(" We'll rember you when you come back, " + username + "!")
    

     json.load()

    import json
    
    filename = 'numbers.json'
    with open(filename) as f_obj:
        number = json.load(f_obj)#读取文件内容到内存中
    print(number)
    
  • 相关阅读:
    洛谷 P1635 跳跃
    python write() argument must be str, not bytes
    python write() argument must be str, not bytes
    Python hashlib Unicode-objects must be encoded before hashing
    Python hashlib Unicode-objects must be encoded before hashing
    洛谷P1629 邮递员送信
    TypeError: Error when calling the metaclass bases Cannot create a consistent method resolution
    TypeError: Error when calling the metaclass bases Cannot create a consistent method resolution
    [USACO07FEB]银牛派对Silver Cow Party
    [USACO09OPEN]捉迷藏Hide and Seek
  • 原文地址:https://www.cnblogs.com/MR---Zhao/p/12348638.html
Copyright © 2020-2023  润新知