python--从入门到实践--chapter 10 文件及错误
发布日期:2021-07-01 03:39:31 浏览次数:2 分类:技术文章

本文共 3805 字,大约阅读时间需要 12 分钟。

文件的读写:

with open(filename, 'a', encoding='utf-8') as file:

with :后面不必写close文件

第二个参数:‘a’ 追加;‘w’ 写;‘r’ 读
encoding = ‘utf-8’ 编码格式,中文的话一般写上

enter = 'y'while enter == 'y':    name = input("请输入你的名字:")    filename = "guest_record.txt"    if name != "":        with open(filename, 'a', encoding='utf-8') as file:            file.write(name + '\n')        print("hello, ", name, " !")        conti = 'y'        while conti == 'y':            reason = input("你为什么喜欢python?")            with open(filename, 'a', encoding='utf-8') as file:                file.write(reason + '\n')            conti = input("继续输入原因吗?y/n ")    enter = input("继续访问吗?y/n ")

file.readlines() 文件按行读取存在列表内

file.read() 整体读取

filename = 'pi_digits.txt'with open(filename) as pi_file: #with帮助我们适时关闭文件    lines = pi_file.readlines()	#把文件按行存储pi_str = ''for line in lines:    pi_str += line.strip()	#strip()行左右的空删除print(pi_str[:7]+"...")print(len(pi_str))birthday = input("输入你的生日:yyyymmdd ")if birthday in pi_str:    print("你的生日出现在pi中。")else:    print("你的生日不在pi中。")
filename = 'learning_python.txt'with open(filename) as file:    '''方法1:整个文件一次读取'''    # print(file.read())    '''方法2:分行读取'''    # for line in file.readlines():    #     print(line.strip())    '''方法3'''    line1 = file.readlines()for l in line1:    print(l.replace("Python", "C++").strip())

try;except;else(try代码块出错后,执行except部分,未出错,执行else)

错误处理可以使程序不至于崩溃,还可以继续运行

print("input 2 numbers to divide, enter 'q' to quit.")while True:    first = input("\nfirst num: ")    if first == 'q':        break    second = input("\nsecond num: ")    try:        answer = int(first) / int(second)    except ZeroDivisionError:        print("divide zero!!!")    else:        print(answer)    breakfilename = 'learning_python.txt'try:    with open(filename) as f_obj:        contents = f_obj.read()except FileNotFoundError:    msg = "Sorry, the file " + filename + " does not exist."    print(msg)    # pass  #一言不发,跳过else:    words = contents.split()    print("the title ", filename, " has ", str(len(words)), " words.")while True:    print("input 2 nums : ")    try:        a = int(input('first num: '))    except ValueError:        print("请输入数字!")        continue    try:        b = int(input('second num: '))    except ValueError:        print("请输入数字!")        continue    print("sum of two nums is ", a+b)

json文件存储

json.dump(object, file)json.load(file)
import jsonnumbers = [2, 3, 5, 7, 11, 13]filename = "numbers.json"with open(filename,'w') as file:    json.dump(numbers,file)with open(filename) as file:    numbers = json.load(file)print(numbers)def get_stored_username():    filename = "username.json"    try:        with open(filename) as file:            username = json.load(file)    except FileNotFoundError:        return None    else:        return usernamedef get_new_username():    username = input("What is your name? ")    filename = "username.json"    with open(filename, 'a') as file:        json.dump(username, file)    return usernamedef greet_user():    username = get_stored_username()    if username:        print("Welcome back, ", username, " !")    else:        get_new_username()        print("We'll remember you when you come back, ", username, " !")greet_user()
import jsondef get_num():    try:        global favor_num        favor_num = int(input("输入你喜欢的数字:"))    except ValueError:        print("你输入的不是数字,请重新输入!")        get_num()    return favor_numdef store_num(num):    filename = "user_favor_num.json"    with open(filename, 'a') as file:        json.dump(num, file)def getAndStore():    store_num(get_num())def print_num():    filename = "user_favor_num.json"    try:        with open(filename) as file:            num = json.load(file)    except FileNotFoundError:        getAndStore()    else:        print("i know your favorite number! it is ", num)print_num()

转载地址:https://michael.blog.csdn.net/article/details/89217528 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:python--从入门到实践--chapter 11 代码测试unittest
下一篇:python--从入门到实践--chapter 9 类

发表评论

最新留言

很好
[***.229.124.182]2024年05月08日 02时43分42秒