python-修改文件

1、修改文件1

# fw = open('username','w')
# fw.write('hhhh')
# fw.flush()  #强制把缓冲区里面的数据写到磁盘上

1、简单粗暴直接
#  1、打开一个文件,获取到他的所有内容
#  2、对内容进行修改
#  3、清空原来文件的内容
#  4、把新的内容写进去
#syz_niuhanyang,78910 syz_zll,78910 syz_fyr,78910
f = open('username','a+')
f.seek(0)
all_str = ''
for s in f:
   new_s ='syz_'+s
   all_str=all_str+new_s
f.seek(0)
f.truncate() #清空文件内容
f.write(all_str)
f.close()

2、打开2个文件
# a文件
# 写一行写到b文件
# a.txt a.txt.bak
# 删掉a文件,b文件名字改成a文件名
# flower
import os
with open('words',encoding='utf-8') as fr,open('.words.bak','w',encoding='utf-8') as fw:
   for line in fr:
      new_line = line.replace('','flower')  #替换字符
      fw.write(new_line)
os.remove('words') #删除文件
os.rename('.words.bak','words') #改名

3、json

import json

f = open('product.json',encoding='utf-8')
res = f.read()
product_dic = json.loads(res)  #json串,变成python的数据类型
print(json.load(f)) #传一个文件对象,它会帮你读文件


d =  {
   'zll':{
      'addr':'北京',
      'age':28
   },
   'ljj':{
      'addr':'北京',
      'age':38
   }
}
fw = open('user_info.json','w',encoding='utf-8')
dic_json = json.dumps(d,ensure_ascii=False,indent=4)  #字典转成json,字典转成字符串
fw.write(dic_json)

json.dump(d,fw,ensure_ascii=False,indent=10)  #操作文件

读写文件函数

import json
def op_data(filename,dic=None):
   if dic:#写入进去
      with open(filename,'w',encoding='utf-8') as fw:
         json.dump(dic,fw,ensure_ascii=False,indent=4)
   else:
      with open(filename,encoding='utf-8') as fr:
         return json.load(fr)


FILE_NAME = 'user_info.json'
all_users = op_data(FILE_NAME)
for i in range(3):
   choice = input('输入,1注册,2、删除')
   if choice=='1':
      username = input('usenrame:')
      pwd = input('pwd:')
      if username not in all_users:
         all_users[username]=pwd
         op_data(FILE_NAME,all_users)
   elif choice=="2":
      username = input('usenrame:')
      all_users.pop(username)
      op_data(FILE_NAME, all_users)

import json    

   dic = {"name":"niuniu","age":18}

   print(json.dumps(dic))#把字典转成json串

   fj = open('a.json','w') 

   print(json.dump(dic,fj))#把字典转换成的json串写到一个文件里面

   s_json = '{"name":"niuniu","age":20,"status":true}'

   print(json.loads(s_json))#把json串转换成字典

   fr = open('b.json','r')

   print(json.load(fr))#从文件中读取json数据,然后转成字典

原文地址:https://www.cnblogs.com/duanjialin007/p/8886445.html