python极简笔记——文件操作

#文件操作

#1.读取文件
#打开文件,关键字with 在不再需要访问文件后将其关闭
with open('data\data1.txt') as fobj:
  #读取文件内容
  contents = fobj.read()
  print(contents)
  
#逐行读取
with open('data\data1.txt') as f:
  for line in f:
    print("read line:",line)

#读取文件的各行到列表中
with open('data\data1.txt') as fo:
  lines = fo.readlines()
for line in lines:
  print('list:',line)
  
#文件写入
def writeToFile(str):
  #w 写模式(会覆盖) r 读模式 r+读写模式 a追加模式(不会覆盖)
  with open('data\wdata1.doc','a') as fw:
    fw.write(str+'\n')
    fw.write(str+str)
writeToFile("python !!!")

#存储json数据
#使用json.dump()存储数据

import json
numbers = [1,2,3,4,5]
with open('data/number.json','w') as jf:
  json.dump(numbers,jf)

#使用json.load()加载数据  
with open('data/number.json') as jr:
  nums = json.load(jr)
print(nums)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值