10-1 python学习笔记
代码:
with open('input.txt') as input: print(input.read()) with open('input.txt') as input: file_in = input print(file_in.read()) list = [] with open('input.txt') as input: for line in input: list.append(line) print(list)
结果:
This is a input file.
It is used to memorize python notes.
This is a input file.
It is used to memorize python notes.
['This is a input file.\n', 'It is used to memorize python notes.']
10-3 访客:
代码:
name = "" while True: name = input("请输入你的名字,输入exit退出程序:") if name == "exit": break print("Hello," + name) with open('guest_book.txt', 'a') as output: output.write(name + "\n") with open('guest_book.txt') as input: print(input.read())
结果:
请输入你的名字,输入exit退出程序:AmyHello,Amy请输入你的名字,输入exit退出程序:JohnHello,John请输入你的名字,输入exit退出程序:exitAmy
John
10-8 猫和狗
代码:
try: with open("cats.txt") as input: print("The cats:") print(input.read()) except FileNotFoundError: print("cats.txt文件未找到") try: with open("dogs.txt") as input: print("The dogs:") print(input.read()) except FileNotFoundError: print("dogs.txt文件未找到")
结果:
The cats:AmeKaraSosoThe dogs:LekoMaka
Racoo
将cats.txt文件移走后:
cats.txt文件未找到The dogs:LekoMakaRacoo
10-11 喜欢的数字
代码:
import json num = input("Your favorite number:") filename = "num.json" with open(filename, "w") as output: json.dump(num, output) with open(filename) as input: num = json.load(input) print("I know your favorite number! It's " + str(num))
结果:
Your favorite number:12
I know your favorite number! It's 12
结果: