"""
一.有如下文件,1.txt,里面的内容为:
键盘敲烂,
月薪过万,
键盘落灰
狗屎一堆
"""
"""
分别完成以下功能:
a:将原文件全部读出来并打印
b:在原文件后面追加一行内容:信不信由你,反正我信了.
c:将原文件全部读出来,并在后面添加一行内容:信不信由你,反正我信了
d:将原文件全部清空,换成下面的内容:
每天坚持一点,
每天努力一点,
慢慢你会发现,
你的进步越来越大.
e:将原文件内容全部读取出来
并在'键盘落灰'这一行的前面加一行,'年薪百万'
然后将更改之后的新内容,写入到一个新文件:a1.txt
"""
# a:将原文件全部读出来并打印
with open('1.txt',mode='r',encoding='utf-8') as fp:
res = fp.read()
print(res)
# b:在原文件后面追加一行内容:信不信由你,反正我信了.
with open('1.txt',mode='a',encoding='utf-8') as fp:
fp.write("\n\t信不信由你,反正我信了.")
# c:将原文件全部读出来,并在后面添加一行内容:信不信由你,反正我信了
with open('1.txt',mode='a+',encoding='utf-8') as fp:
print(fp.read())
fp.write("\n\t信不信由你,反正我信了.")
# d:将原文件全部清空,换成下面的内容:
with open('1.txt',mode='w',encoding='utf-8') as fp:
res = """\t每天坚持一点,
每天努力一点,
慢慢你会发现,
你的进步越来越大.
"""
fp.write(res)
# e:将原文件内容全部读取出来,并在'键盘落灰'这一行的前面加一行,'年薪百万',然后将更改之后的新内容,写入到一个新文件:a1.txt
with open('1.txt',mode='r+',encoding='utf-8') as fp:
lst = fp.readlines()
print(lst)
lst.insert(-2,"\t年薪百万,\n")
with open('a1.txt',mode='w+',encoding='utf-8') as fp1:
fp1.writelines(lst)
"""
二.有如下文件,1.txt,里面的内容为:
葫芦娃,葫芦娃,
一根藤上七个瓜,
风吹雨打都不拍,
啦啦啦啦.
分别完成下面的功能:
a:以r+的模式打开原文件,判断原文件是否可读,是否可写
b:以r的模式打开原文件,利用for循环遍历文件对象
c:以r的模式打开原文件,以readlines()方法读取出来,并循序遍历
d:以r模式读取"葫芦娃,葫芦娃,"前四个字符
e:以r模式读取第一行内容,并去除此行前后的空格,制表符,换行符
f:以r模式打开文件,从"风吹雨打...."开始读取,一直读到最后
g:以a+模式打开文件,先追加一行:"喜洋洋与灰太狼"然后再全部读取出来
h:截取原文件,截取内容:"葫芦娃,葫芦娃"
"""
# a:以r+的模式打开原文件,判断原文件是否可读,是否可写
with open('a1.txt', mode="r+", encoding="utf-8") as fp1:
print(fp1.readable(), fp1.writable())
# b:以r的模式打开原文件,利用for循环遍历文件对象
with open('a1.txt', mode="r", encoding="utf-8") as fp2:
for line in fp2:
print(line.strip())
# c:以r的模式打开原文件,以readlines()方法读取出来,并循序遍历
with open('a1.txt', mode="r", encoding="utf-8") as fp3:
res = fp3.readlines()
for i in res:
print(i.strip())
# d:以r模式读取"葫芦娃,葫芦娃,"前四个字符
with open('a1.txt', mode="r", encoding="utf-8") as fp4:
print(fp4.read(4))
# e:以r模式读取第一行内容,并去除此行前后的空格,制表符,换行符
with open('a1.txt', mode="r", encoding="utf-8") as fp5:
print(fp5.readline().strip())
# f:以r模式打开文件,从"风吹雨打...."开始读取,一直读到最后
with open('a1.txt', mode="r", encoding="utf-8") as fp6:
lst = fp6.readlines()
for i in lst[-2:]:
print(i)
# g:以a+模式打开文件,先追加一行:"喜洋洋与灰太狼"然后再全部读取出来
with open('a1.txt', mode="a+", encoding="utf-8") as fp6:
fp6.write("喜洋洋与灰太狼.")
fp6.seek(0)
print(fp6.read())
# h:截取原文件,截取内容:"葫芦娃,葫芦娃"
with open('a1.txt', mode="r+", encoding="utf-8") as fp7:
fp7.truncate(24)
""""
三.文件内容a.txt内容:每一行内容分别为商品名字,价钱,个数
apple 10 3
tesla 10000 1
mac 3000 2
lenovo 30000 3
chicken 10 3
变成如下数据格式,并计算出总价格
[
{'name':'apple','price':10,'amount':3}
{'name':'tesla','price':10,'amount':1}
]
"""
with open('a1.txt', mode='r', encoding='utf-8') as fp8:
lst = []
total = 0
for i in fp8:
res = (i.strip().split())
dic = {}
dic['name'] = res[0]
dic['price'] = int(res[1])
dic['amount'] = int(res[2])
sum = dic['price'] * dic['amount']
total += sum
lst.append(dic)
print("1.数据格式:", lst)
print("2.总价格:", total)
标签:文件,原文件,utf,读写操作,encoding,mode,txt,open
From: https://www.cnblogs.com/xianyuq/p/18166822