美文网首页
python 读写文件,json,目录

python 读写文件,json,目录

作者: analanxingde | 来源:发表于2018-09-14 10:53 被阅读24次

常见的一些json读写的操作
读取某个目录下的文件

import os
path = "D:/Python34/news" #文件夹目录
files= os.listdir(path) #得到文件夹下的所有文件名称
s = []
for file in files: #遍历文件夹
     if not os.path.isdir(file): #判断是否是文件夹,不是文件夹才打开
          f = open(path+"/"+file); #打开文件
          iter_f = iter(f); #创建迭代器
          str = ""
          for line in iter_f: #遍历文件,一行行遍历,读取文本
              str = str + line
          s.append(str) #每个文件的文本存到list中
print(s)

读取某些json字段

for line in iter_f: #遍历文件,一行行遍历,读取文本
    data_json=json.loads(line)
    wareid=data_json['wareid']#每个文件的文本存到list中
    wareid = filter(str.isdigit,wareid.encode("utf-8"))  //转码为string,否则输出会报错string的indices应为int
    s_old.append(wareid)

读写文件

with open("increase.data","w") as f:
    for item in increase:
        f.write(item+"\n")
f.close()

读取shell参数,参数下标从1开始读取,0为Python脚本名

import sys
x=sys.argv[1]

求差集

taoge@localhost test> sort a.txt | uniq > aa.txt
taoge@localhost test> sort b.txt | uniq > bb.txt
taoge@localhost test> cat aa.txt bb.txt bb.txt | sort | uniq -u

相关文章

网友评论

      本文标题:python 读写文件,json,目录

      本文链接:https://www.haomeiwen.com/subject/rurnwftx.html