Loading... # 文件与错误 ## 文件 ### 读取 ```python with open("pi_digits.txt")as file_object:##file_object写什么都可以,记住就行 contents = file_object.read() print(contents) # 逐行读取 with open("pi_digits.txt") as file_object: for line in file_object:#line的空行与Print的空行 print(line) #取消空行 with open("pi_digits.txt") as file_object: for line in file_object: print(line.rstrip()) file_name = "pi_digits.txt" with open(file_name) as file_object: lines = file_object.readlines() #包含文件内容的列表 for line in lines: print(line.rstrip()) pi_string = "" for line in lines: pi_string += line.rstrip() print(pi_string) pi_string = "" for line in lines: pi_string += line.strip() print(pi_string) pi = float(pi_string) print(pi * 2) with open("pi_million_digits.txt") as file_object: lines = file_object.readlines() pi_string = "" for line in lines: pi_string += line.strip() print(pi_string[:52]) birthday = input("Enter your birthday, int the form mmddyy") if birthday in pi_string: print("Your birthday appears in the first million digits of pi!") else: print("Your birthday does not appear in the first million digits of pi!") ``` 结果 ``` 3.1415926535 8979323846 2643383279 3.1415926535 8979323846 2643383279 3.1415926535 8979323846 2643383279 3.1415926535 8979323846 2643383279 3.1415926535 8979323846 2643383279 3.141592653589793238462643383279 6.283185307179586 3.14159265358979323846264338327950288419716939937510 Enter your birthday, int the form mmddyy121400 Your birthday appears in the first million digits of pi! ``` ### 写入 ```python filename = "programming.txt" with open(filename, "w") as file_object: file_object.write("I love programming.\n")#python只能写入字符串 file_object.write("I love creating new games.\n") with open(filename, "a") as file_object:#追加 file_object.write("I also love finding meaning in large datasets.\n") file_object.write("I love creating apss that can run in a browser.\n") ``` **json** ```python import json numbers = [2, 3, 5, 7, 11, 13] filename = 'numbers.json' with open(filename, 'w') as f: json.dump(numbers, f) ``` ```python import json filename = "numbers.json" with open(filename) as f: numbers = json.load(f) print(numbers) ``` ## 错误 处理错误以防崩溃 ```python filename = "alice.txt" def count_words(filename): try: with open(filename, encoding="utf-8") as f: contents = f.read() except FileNotFoundError: # print(f"Sorry, the file {filename} does not exist.") pass#静默失败,'pass'表示什么也不做,同时充当占位符 else: words = contents.split() num_words = len(words) print(f"The file {filename} has about {num_words} words.") filenames = ["alice.txt", "FILE NOT EXIST.txt","siddhartha.txt", "moby_dick.txt", "little_women.txt"] for filename in filenames: count_words(filename) ``` **在项目中新加的玩意** main.py ```python def import_info(filename: str) -> list: try: with open(filename) as f: info = json.load(f) dragons = [] except FileNotFoundError:#其实没有好多用,文件内容可能不正确,等等 print(f"{filename} not found") exit() else: for key in info: dragons.append(dragon.Dragon(key[0], key[1], key[2], key[3], key[4], key[5])) return dragons ``` ```python while True: try: self.player_choice(int(input()), key) except ValueError: print("Please check your input") else: break ``` ## 重构 >你经常会遇到这样的情况:代码能够正确地运行,但通过将其划分为一系列完成具体工作的函数,还可以改进。这样的过程称为重构 。重构让代码更清晰、更易于理解、更容易扩展。 学习后面的项目时就会发现重构的重要性,比如在重构函数的基础上重构 Last modification:January 30, 2022 © Allow specification reprint Like 如果觉得我的文章对你有用,请留下评论。