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)

你可能感兴趣的:(磨刀不误,平实,python,开发语言,后端)