python基础代码存放

 关于file文件的部分


filename = 'demo.py'
lst1 = ['0\n' for i in range(100)]
lst2 = [str(i)+'\n' for i in range(100)]

with open(filename, 'w') as fp:
    fp.writelines(lst1)
    fp.writelines(lst2)
fp.close()

with open(filename, 'r') as fp:
    lines = fp.readlines()
maxLength = len(max(lines, key=len))
fp.close()

lines = [line.rstrip().ljust(maxLength)+'#'+str(index)+'\n' for index, line in enumerate(lines)]
with open(filename[:-3]+'_new.py', 'w') as fp:
    fp.writelines(lines)
fp.close()


import json
#写入
filename ='Json.json'
word_map={
    "supercategory": "person",
    "id": 1,
    "name": "person",
    "c": ["nose","left_eye","right_eye","left_ear","right_ear","left_shoulder","right_shoulder","left_elbow","right_elbow","left_wrist","right_wrist","left_hip","right_hip","left_knee","right_knee","left_ankle","right_ankle"],
    "skeleton": [[16,14],[14,12],[17,15],[15,13],[12,13],[6,12],[7,13],[6,7],[6,8],[7,9],[8,10],[9,11],[2,3],[1,2],[1,3],[2,4],[3,5],[4,6],[5,7]]
}
with open(filename, 'w') as j:
    json.dump(word_map, j)
#读取
with open('Json.json', 'r', encoding='utf8') as f:
    json_data = json.load(f)
    for j in json_data.items():
        print(j)



from os.path import isdir, join, splitext, getsize
from os import remove, listdir
import sys
def Delete(path):
    if isdir(path):
        for item in listdir(path):
            item = join(path, item)
            if isdir(item) == False:
                if splitext(item)[1] in extension or getsize(item) == 0:
                    remove(item)
                    print(item, "deleted")
            else:
                Delete(item)

extension = ['.txt']#删除后缀为txt的文件
path = "D:\_SoftTools\pythonProject1"
Delete(path)

Pickle模块的使用:参考教材7.3.1,编写pickle文件的写入和读取
写入二进制文件
import pickle
i=13000000
a=99.056
s='中国人民123abc'
lst=[[1,2,3],[4,5,6],[7,8,9]]
tu=(-5,10,8)
coll={4,5,6}
dic={'a':'apple','b':'banana','g':'grape','o':'orange'}
data=[i,a,s,lst,tu,coll,dic]
with open('sample_pickle.dat','wb') as f:
    try:
        pickle.dump(len(data),f)
        for item in data:
            pickle.dump(item,f)
    except:
        print('写文件异常')
#读取二进制文件
import pickle
with open('sample_pickle.dat','rb')as f:
    n=pickle.load(f)
    for i in range(n):
        x=pickle.load(f)
        print(x)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值