文件读写和序列化

python 文件读写和序列化学习。

python文件读写

1 打开并且读取文件

  1. f = open('openfile.txt','r')
  2. print(f.read())
  3. f.close()

<!--more-->

2 打开并且读取一行文件

  1. f = open('openfile.txt','r')
  2. print(f.readline())
  3. f.close()

3 打开并以二进制形式读取文件

  1. f = open('./openfile.txt','rb')
  2. print(f.read())
  3. f.close()

4 打开并自动关闭文件

  1. with open('openfile.txt','r') as f:
  2. print(f.read())

5 读取所有行

  1. f = open('openfile.txt','r')
  2. for line in f.readlines():
  3. print(line.strip())
  4. f.close()

6 以gbk方式读取文件

  1. f = open('openfiles.txt','r',encoding='gbk' )
  2. print(f.read())
  3. f.close()

7 以追加方式写

  1. with open('openfile.txt', 'a') as f:
  2. f.write('\n')
  3. f.write('Hello World!!!')

python IO操作

1 StringIO 写字符串

  1. from io import StringIO
  2. f = StringIO()
  3. f.write('hello')
  4. f.write(' ')
  5. f.write('world !')
  6. print(f.getvalue() )

2 StringIO 读取字符串

  1. from io import StringIO
  2. f = StringIO("Hello\nWorld\nGoodBye!!")
  3. while True:
  4. s = f.readline()
  5. if(s==''):
  6. break
  7. print(s.strip())

3 BytesIO 读写二进制字符

  1. from io import BytesIO
  2. f = BytesIO()
  3. f.write('中文'.encode('utf-8') )
  4. print(f.getvalue())
  5. from io import BytesIO
  6. f = BytesIO(b'\xe4\xb8\xad\xe6\x96\x87')
  7. f.read()

python环境变量和目录

1 打印系统的名字和环境变量

  1. import os
  2. print(os.name)
  3. print(os.environ)

2 获取指定key值得环境变量

  1. print(os.environ.get('PATH'))

3 相对路径转化绝对路径

  1. print(os.path.abspath('.'))

4 在某个目录下创建一个新的目录

  1. #首先把新目录的完整路径表示出来
  2. print(os.path.join('/Users/michael','testdir') )
  3. # 然后创建一个目录:
  4. #print(os.mkdir('/Users/michael/testdir') )
  5. # 删掉一个目录:
  6. #print(os.rmdir('/Users/michael/testdir') )

5 路径切割

  1. print(os.path.split('/path/to/file.txt') )
  2. print(os.path.splitext('/path/to/file.txt') )

6 文件重命名和删除

  1. #print(os.rename('test.txt', 'test.py') )
  2. #print(os.remove('test.py'))

7 列举当前目录下所有目录和py文件

  1. print([x for x in os.listdir('.') if os.path.isdir(x) ])
  2. print([x for x in os.listdir('.') if os.path.isfile(x) and os.path.splitext(x)[1] == '.py'])

python序列化

1 序列化为二进制

  1. import pickle
  2. d = dict(name='Bob', age=20, score=88)
  3. print(pickle.dumps(d))

2 序列化写入文件

  1. f = open('openfile3.txt','wb')
  2. print(pickle.dump(d, f) )
  3. f.close()

3 反序列化读取文件

  1. f = open('openfile3.txt','rb')
  2. d = pickle.load(f)
  3. f.close()
  4. print(d)

4 序列化为json

  1. import json
  2. class Student(object):
  3. def __init__(self, name, age, score):
  4. self.name = name
  5. self.age = age
  6. self.score = score
  7. def convertFunc(std):
  8. return {'name':std.name,
  9. 'age':std.age,
  10. 'score':std.score}
  11. s = Student('Bob', 20, 88)
  12. print(json.dumps(s,default=convertFunc))
  13. print(json.dumps(s,default=lambda obj:obj.__dict__))

5 反序列化

  1. def revert(std):
  2. return Student(std['name'], std['age'], std['score'])
  3. json_str = '{"age": 20, "score": 88, "name": "Bob"}'
  4. print(json.loads(json_str, object_hook=revert ) )
热门评论

热门文章

  1. Linux环境搭建和编码

    喜欢(594) 浏览(12294)
  2. 解密定时器的实现细节

    喜欢(566) 浏览(3496)
  3. slice介绍和使用

    喜欢(521) 浏览(2488)
  4. C++ 类的继承封装和多态

    喜欢(588) 浏览(5008)
  5. windows环境搭建和vscode配置

    喜欢(587) 浏览(2838)

最新评论

  1. C++ 并发三剑客future, promise和async Yunfei:大佬您好,如果这个线程池中加入的异步任务的形参如果有右值引用,这个commit中的返回类型推导和bind绑定就会出现问题,请问实际工程中,是不是不会用到这种任务,如果用到了,应该怎么解决?
  2. Qt MVC结构之QItemDelegate介绍 胡歌-此生不换:gpt, google
  3. 聊天项目(9) redis服务搭建 pro_lin:redis线程池的析构函数,除了pop出队列,还要free掉redis连接把
  4. 答疑汇总(thread,async源码分析) Yagus:如果引用计数为0,则会执行 future 的析构进而等待任务执行完成,那么看到的输出将是 这边应该不对吧,std::future析构只在这三种情况都满足的时候才回block: 1.共享状态是std::async 创造的(类型是_Task_async_state) 2.共享状态没有ready 3.这个future是共享状态的最后一个引用 这边共享状态类型是“_Package_state”,引用计数即使为0也不应该block啊

个人公众号

个人微信