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 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
很好
[***.229.124.182]2024年05月08日 02时43分42秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
java并发编程(十一)-常用的并发工具类
2019-05-03
shell脚本中 EOF的意思
2019-05-03
Springboot使用详解
2019-05-03
java并发编程(十五)-LockSupport工具类
2019-05-03
Spring源码分析(七) - bean的生命周期
2019-05-03
leetcode算法 111. 二叉树的最小深度
2019-05-03
李洪强iOS开发之-cocopods安装
2019-05-03
界面反应非常慢
2019-05-04
ios等待ualertview弹出动画完成后再跳转至其他页面
2019-05-04
实现string toHex(int)把一个十进制转换成十六进制。(完全用算法实现)
2019-05-04
内部排序算法比较
2019-05-04
函数指针和函数引用的区别
2019-05-04
哲理故事三百篇(1-50) 8
2019-05-04
有谁能,为你戴上纸戒指?
2019-05-04
有没有一篇文章,让你黯然神伤?却又牵动着你灵魂深处的希望?
2019-05-04
吵架之后-----
2019-05-04
男生和女生为什么会不一样呢?------
2019-05-04
知道什么是爱情吗?如果不知道,请看:如果在天堂遇见你,你还记不记得我是谁?
2019-05-04
大家觉得这篇文章如何?
2019-05-04