1 #IO.py 2 import sys, os 3 #f=open('/python_workspace/IO/readme', 'r') 4 5 #print(f) 6 #sys.exit() 7 #print(f.read()) 8 9 #print(os.system('dir')) 10 11 ''' 12 f1=open('hello', 'a+') 13 f1.write('hello mofei004 ') 14 f1.close() 15 f1=open('hello', 'r') 16 print(f1.read()) 17 18 19 with open('/python_workspace/IO/readme', 'r') as f: 20 print(f.readlines())#读取多行,并以list的形式返回 21 # print(f.readline())#读取单行 22 # print(f.read(3))#会影响当前文档指针,返回时并不复位 23 # print(f.read()) 24 #文件已经关闭了 25 #print(f.read()) 26 27 #打印文档中的每一行 28 with open('/python_workspace/IO/readme', 'r') as f: 29 print(f.read()) 30 for line in f.readlines(): 31 print(line.strip())#strip()不输出 32 33 #包含非法字符时,会有UnicodeDecodeError,下面这种方式忽略了非法字符 34 f=open('/python_workspace/wrong.txt', 'a', encoding='gbk', errors='ignore') 35 36 37 with open('/python_workspace/IO/readme', 'a+') as f: 38 f.write('good day ') 39 40 #字符串前的r,防止字符串前的转义字符 41 fpath = r'C:Windowssystem.ini' 42 ''' 43 ######### 44 # StringIO:内存中的字符串读写 45 ######### 46 ''' 47 from io import StringIO 48 #f = StringIO() 49 50 #print(f.write('hello')) 51 #print(f.getvalue()) 52 53 f=StringIO('Hello! Hi! Goodbye!') 54 while True: 55 s=f.readline() 56 if s== '': 57 break; 58 print(s.strip())#strip()不输出 59 60 ######### 61 #BytesIO:内存中操作二进制数据 62 ######### 63 from io import BytesIO 64 f1 = BytesIO() 65 f1.write('中文'.encode('utf-8')) 66 print(f1.getvalue()) 67 68 f2 = BytesIO(b'xe4xb8xadxe6x96x87') 69 print(f2.read()) 70 71 ######### 72 #操作文件及目录 73 ######### 74 #print(os.name) 75 #print(os.uname())#Linux系统才支持这么命令 76 #print(os.environ()) 77 #os中的某些函数是和操作系统相关的 78 #print(help(os)) 79 print(os.path.abspath('.')) 80 s = os.path.abspath('.') 81 p = os.path.join(s, 'testdir') 82 print(p) 83 #即可判断路径,也可判断文件,本质是一样的 84 if not os.path.exists(p): 85 os.mkdir(p) 86 os.rmdir(p) 87 ''' 88 #判断文件的读下权限 89 #os.access(path, mode) 90 ''' 91 os.F_OK: 检查文件是否存在; 92 os.R_OK: 检查文件是否可读; 93 os.W_OK: 检查文件是否可以写入; 94 os.X_OK: 检查文件是否可以执行 95 ''' 96 97 #也可用try和pathlib模块来判断路径是否存在 98 ''' 99 os.path.join()#合并两个路径 100 os.path.split()#拆分路径为两个部分,后一部分总是最后级别的目录或文件名: 101 ''' 102 ''' 103 print(os.path.split(s)) 104 print(os.path.splitext(s+'IO.py')) 105 106 #os.mknod('test.txt') 107 with open('test.txt', 'w+') as f: 108 pass 109 os.rename('test.txt', 'test.py') 110 os.remove('test.py') 111 112 #import shutil 113 #copyfile()可以复制文件 114 os.listdir('.') 115 116 #筛选出当前目录下存在的文件夹 117 print([x for x in os.listdir('.') if os.path.isdir(x)]) 118 119 #筛选出当前目录下.py文件 120 print([x for x in os.listdir('.') if os.path.isfile(x) and os.path.splitext(x)[1]=='.py']) 121 ''' 122 ########### 123 #序列化 124 ########### 125 ''' 126 import pickle 127 d = dict(name='Bob', age=20, score=88) 128 #以二进制打印d的内容 129 print(pickle.dumps(d)) 130 131 f = open('dump.txt', 'wb') 132 #把d二进制存储于文件中 133 pickle.dump(d, f) 134 f.close() 135 136 f = open('dump.txt', 'rb') 137 #从文件中读出二进制内容 138 d = pickle.load(f) 139 f.close() 140 print(d) 141 ''' 142 ''' 143 JSON类型 Python类型 144 {} dict 145 [] list 146 "string" str 147 1234.56 int或float 148 true/false True/False 149 null None 150 ''' 151 import json 152 d=dict(name='Bob', age=20, score=88) 153 154 #序列化为Json 155 with open('/python_workspace/IO/json', 'w+') as f: 156 f.write(json.dumps(d)) 157 158 #反序列化Json 159 json_str = '{"age": 20, "score": 88, "name": "Bob"}' 160 print(json.loads(json_str)) 161 162 163 #序列化一个类对象 164 class Student(object): 165 def __init__(self, name, age, score): 166 self.name = name 167 self.age = age 168 self.score = score 169 170 def student2dict(std): 171 return { 172 'name':std.name, 173 'age':std.age, 174 'score':std.score 175 } 176 s=Student('Bob', 20, 88) 177 #通过student2dict把Student对象装换为dict 178 print(json.dumps(s, default=student2dict)) 179 #通常class的实例都有一个__dict__属性,就是一个dict,用来存储实例的变量 180 print(json.dumps(s, default=lambda obj: obj.__dict__)) 181 182 #反序列化为类对象 183 def dict2student(d): 184 return Student(d['name'], d['age'], d['score']) 185 json_str='{"age":20,"score":88, "name":"mofei004"}' 186 print(json.loads(json_str, object_hook=dict2student)) 187 188 189 obj = dict(name='小明', age=20) 190 #ensure_ascii确保输出的数据均为ascii码 191 s = json.dumps(obj, ensure_ascii=True) 192 print(s)