文件的基本操作

文件的基本操作:只读,只写,追加,读写,写读

encoding必须标明要操作文件的编码,否则会出错。

r:只读,文件不存在时报错
w:只写,先清空文件内容,再写入内容。
a:追加,在原文件内容后面追加新的内容。

rb:二进制方式读取
wb:二进制方式写入
ab:二进制方式追加

r+:读写,先读取原文件的内容,后将内容写入文件
w+:写读
a+:写读

r+b
w+b
a+b
# ------------------读写 r+   先读取原文件的内容,后将内容写入文件 ------------------------------
# f = open('some', 'r+', encoding='utf-8')
# s = f.read()
# print(s)
# w = f.write('真的')
# f.close()

# f = open('some', 'r+b')
# s = f.read()
# print(s)
# w = f.write('真的'.encode('utf-8'))
# f.close()

# ----------------- 写读 w+ 先清空原文件内容,然后写入信息,读取的内容为空--------------
# f = open('some', 'w+', encoding='utf-8')
# w = f.write('a')
# s = f.read()
# print(s)
# f.close()

# f = open('some', 'w+b')
# w = f.write('88888'.encode('utf-8'))
# s = f.read()
# print(s)
# f.close()
View Code

 文件修改

1.将文件逐行加载,逐行修改进入内存,完成后覆盖旧文件

import os
with open('hello', 'r', encoding='utf-8') as re_hello, open('.a.txt.swap','w',encoding='utf-8') as wr_pei:
    for i in re_hello:
        i = i .replace('SB', 'Alex')
        wr_pei.write(i)
os.remove('hello')
os.renames('.a.txt.swap', 'hello')
View Code

 

2.将文件全部加载进入内存,修改后覆盖旧文件。(若文件太大,读入内存时会卡)

import  os
with open('hello', 'r',encoding='utf-8') as re_hello,open('.write', 'w', encoding='utf-8') as wr_hello:
    data = re_hello.read()
    data = data.replace('Alex', 'SUshan')
    wr_hello.write(data)
os.remove('hello')
os.renames('.write', 'hello')
View Code

练习:

文件a.txt内容:每一行内容分别为商品名字,价钱,个数。

apple 10 3
tesla 100000 1
mac 3000 2
lenovo 30000 3
chicken 10 3
通过代码,将其构建成这种数据类型:[{'name':'apple','price':10,'amount':3},{'name':'tesla','price':1000000,'amount':1}......] 并计算出总价钱。

练习
list = []
with open('a', 'r', encoding='utf-8') as fife:
    for i in fife:
        i = i.strip()
        s = i.split(' ')
        # print(s)
        dic = {'name': s[0],
               'price': s[1],
               "amount":s[2]}
        list.append(dic)
print(list)
su = 0
for i in list:
    su += int(i['price'])*int(i['amount'])
print(su)
答案

 

posted @ 2019-01-16 16:29  夜色迟暮  阅读(111)  评论(0编辑  收藏  举报