python 读写文件,json,目录

2018-09-14  本文已影响24人  analanxingde

常见的一些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
上一篇 下一篇

猜你喜欢

热点阅读