编写一个程序, 它读取这个文件, 并将你所写的内容打印三次:
第一次打印时读取整个文件;
第二次打印时遍历文件对象;
第三次打印时将各行存储在一个列表中, 再在with 代码块外打印它们。
文本文件

主函数
with open('learning_python.txt') as digits:
digit=digits.read()
print(digit)
with open('learning_python.txt') as digits:
for a in digits:
print(a)
with open('learning_python.txt') as digits:
lines=digits.readlines()
for a in lines:
print(a)
运行结果


message = “I really like dogs.”
message.replace(‘dog’, ‘cat’) ‘I
really like cats.’读取你刚创建的文件learning_python.txt中的每一行, 将其中的Python都替换为另一门语言的名称, 如C。将修改后的各行都打印到屏幕上。
with open('learning_python.txt') as digits:
digit=digits.readlines()
for di in digit:
di=di.replace('Python','C')
print(di)

name=input("用户输入名字;")
with open('guest.txt','w') as guest:
guest.write(name)
输入

输出文本文件

主函数
with open('guest_book.txt','w') as guest:
name=True
while name:
name = input("用户输入名字;")
if name!='':
print(f"欢迎您,{name}")
guest.write(name+'\n')
输入

输出文本文件

和10-4差不多,略
在用户输入的任何一个值不是数字时都捕获TypeError 异常, 并打印一条友好的错误消息。 对你编写的程序进行测试: 先输入两个数字,再输入一些文本而不是数字。
try:
a = int(input("输入第一个加数:"))
except ValueError:
print("用户输入两个数字,而不是文本")
try:
b = int(input("输入第二个加数:"))
print(a + b)
except ValueError:
print("用户输入两个数字,而不是文本")



sum = 0
while True:
try:
digit = int(input("输入加数:"))
except ValueError:
digit=0
print("用户输入两个数字,而不是文本")
sum += digit
if sum>10:
break
print(sum)

编写一个程序, 尝试读取这些文件,并将其内容打印到屏幕上。
将这些代码放在一个try-except 代码块中,以便在文件不存在时捕获FileNotFound 错误, 并打印一条友好的消息。
将其中一个文件 移到另一个地方, 并确认except代码块中的代码将正确地执行。
输入三只狗名字

with open('dogs.txt','w') as dogs:
i = 0
while i < 3:
dog=input("输入狗的名字:")
if i<2:
dogs.write(dog+'\n')
else:
dogs.write(dog)
i += 1
print("三只狗名字输入进dogs.txt完毕")
输入三只猫名字

with open('cats.txt','w') as cats:
i = 0
while i < 3:
cat=input("输入猫的名字:")
if i<2:
cats.write(cat+'\n')
else:
cats.write(cat)
i += 1
print("三只猫名字输入进cats.txt完毕")
主函数
import cats,dogs #输入三只猫和三只狗并创建两个文件
try:
with open('cats.txt') as cats:
cat=cats.readlines()
except FileNotFoundError:
print("文件找不到")
try:
with open('dogs.txt') as dogs:
dog=dogs.readlines()
except FileNotFoundError:
print("文件找不到")
try:
with open('aaa.txt') as aaa: #故意弄了个没创建的文件
aa=aaa.readlines()
except FileNotFoundError:
print("aaa.txt文件找不到")
for c in cat:
print(c)
for d in dog:
print(d)
输出



猫和狗用的10-8的文件
import cats,dogs #输入三只猫和三只狗并创建两个文件
try:
with open('cats.txt') as cats:
cat=cats.readlines()
except FileNotFoundError:
pass
try:
with open('dogs.txt') as dogs:
dog=dogs.readlines()
except FileNotFoundError:
pass
try:
with open('aaa.txt') as aaa: #故意弄了个没创建的文件
aa=aaa.readlines()
except FileNotFoundError:
pass
for c in cat:
print(c)
for d in dog:
print(d)



你可以使用方法count() 来确定特定的单词或短语在字符串中出现了多少次。 例如, 下面的代码计算’row’ 在一个字符串中出现了多少次:
line = “Row, row, row your boat”
line.count(‘row’)
2
line.lower().count(‘row’)
3
请注意, 通过使用lower() 将字符串转换为小写, 可捕捉要查找的单词出现的所有次数, 而不管其大小写格式如何。
编写一个程序, 它读取你在项目Gutenberg中获取的文件, 并计算单词’the’ 在每个文件中分别出现
with open('hello.txt',encoding='utf-8') as images:
image=images.read()
im=image.count('in')
print(im)

文本内容:
Here Mr. Fleming folded his hands across his capacious cummerbund, and
assumed an expression of benign satisfaction.
“Oh, your best, of course,” quickly assented Mallender. “I did not
come out here with an eye to money. What brought me to India was
to find my Uncle,” and his umbrella struck the matting with such a
vigorous thump, that it raised a little puff of dust. “I have my own
ideas. I’ve given this business a great deal of—er—consideration, and
I don’t mind telling you, I firmly believe my Uncle to be dead, and
that some infernal scoundrel is impersonating him, and living on half
his fortune. Our share was just a bribe to shut our mouths and stifle
inquiries. Now,” suddenly appealing to Mr. Parr, “what do you say?”
“Well, Captain Mallender,” and he gave a laugh of ironical amusement,
“if I must give an opinion, Isay, that your idea would make a
valuable plot for a sixpenny shocker, but that is all there is in it.”
import json
with open('dume.json','w') as put:
digit=input("用户输入喜欢的数字:")
json.dump(digit,put)
with open('dume.json') as out:
userdigit=json.load(out)
print(f"I know your favorite number! It's {userdigit}" )

所输出文件

程序
import json
try:
with open('dum.json') as out:
userdigit=json.load(out)
except FileNotFoundError:
with open('dum.json','w') as put:
digit=input("用户输入喜欢的数字:")
json.dump(digit,put)
else:
print(userdigit)
第一次运行

第二次运行

程序
import json
def get_new_username():
with open('User.json', 'w') as user:
name = input("请创建一个新的用户名:")
json.dump(name, user)
def greet_user():
try:
with open('User.json') as user:
name=input("请输入用户名:")
if name == json.load(user):
print(f"欢迎回来,{name}")
else:
print("输入的用户名错误!")
get_new_username()
except FileNotFoundError:
with open('User.json','w') as user:
name=input("新用户,请创建一个用户名:")
json.dump(name,user)
greet_user()
第一次运行

第二次运行:故意输入错误

第三次运行:这次输入正确
