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)

猜你喜欢

转载自blog.csdn.net/sinat_22808389/article/details/94719338