python 文件读写和序列化学习。
## python文件读写
`1 打开并且读取文件`

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

`2 打开并且读取一行文件`

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

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

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

`4 打开并自动关闭文件`

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

`5 读取所有行`

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

`6 以gbk方式读取文件`

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

`7 以追加方式写`

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

## python IO操作
`1 StringIO 写字符串`

from io import StringIO
f = StringIO()
f.write('hello')
f.write(' ')
f.write('world !')
print(f.getvalue() )

`2 StringIO 读取字符串`

from io import StringIO
f = StringIO("Hello\nWorld\nGoodBye!!")
while True:
s = f.readline()
if(s==''):
break
print(s.strip())

  

`3 BytesIO 读写二进制字符`

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

  

## python环境变量和目录

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

import os
print(os.name)
print(os.environ)

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

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

`3 相对路径转化绝对路径`

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

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

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

`5 路径切割`

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

`6 文件重命名和删除`

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

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

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

## python序列化

`1 序列化为二进制`

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

`2 序列化写入文件`

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

`3 反序列化读取文件`

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

`4 序列化为json`

import json

class Student(object):
def __init__(self, name, age, score):
self.name = name
self.age = age
self.score = score def convertFunc(std):
return {'name':std.name,
'age':std.age,
'score':std.score} s = Student('Bob', 20, 88)
print(json.dumps(s,default=convertFunc))
print(json.dumps(s,default=lambda obj:obj.__dict__))

  

`5 反序列化`

def revert(std):
return Student(std['name'], std['age'], std['score']) json_str = '{"age": 20, "score": 88, "name": "Bob"}'
print(json.loads(json_str, object_hook=revert ) )

  我的微信公众号

python 学习笔记(十二) 文件和序列化的更多相关文章

  1. Python学习笔记(十二)—Python3中pip包管理工具的安装【转】

    本文转载自:https://blog.csdn.net/sinat_14849739/article/details/79101529 版权声明:本文为博主原创文章,未经博主允许不得转载. https ...

  2. python 学习笔记十二 html基础(进阶篇)

    HTML 超级文本标记语言是标准通用标记语言下的一个应用,也是一种规范,一种标准,它通过标记符号来标记要显示的网页中的各个部分.网页文件本身 是一种文本文件,通过在文本文件中添加标记符, 可以告诉浏览 ...

  3. Python学习笔记十二

    HTML全称:Hyper Text Markup Language超文本标记语言 不是编程语言 HTML使用标记标签来描述网页 2.  HTML标签 开始标签,结束标签.  例如:<html&g ...

  4. python学习笔记(十)、文件操作

    在前面我们了解到了没得模块,其中有一个模块为fileinput,为文件操作模块,不知道小伙伴们是否还记得? 1 打开文件 要打开文件,可以使用fileinput中的fileinput.input函数进 ...

  5. python学习笔记(十二)-网络编程

    本文结束使用 Requests 发送网络请求.requests是一个很实用的Python HTTP客户端库,编写爬虫和测试服务器响应数据时经常会用到.可以说,Requests 完全满足如今网络的需求. ...

  6. python 学习笔记十二 CSS基础(进阶篇)

    1.CSS 简介 CSS 指层叠样式表 (Cascading Style Sheets) 样式定义如何显示 HTML 元素 样式通常存储在样式表中 把样式添加到 HTML 4.0 中,是为了解决内容与 ...

  7. python学习笔记(十 二)、操作数据库

    每一种语言都少不了多数据库进行各种操作. python支持多种数据库.有关python支持的数据库清单,请参阅:https://wiki.python.org/moin/DatabaseInterfa ...

  8. python学习笔记十二:类的定义

    demo #!/usr/bin/python class Person: name = 'jim' age = 25 def say(self): print 'My name is ' + self ...

  9. python3.4学习笔记(十二) python正则表达式的使用,使用pyspider匹配输出带.html结尾的URL

    python3.4学习笔记(十二) python正则表达式的使用,使用pyspider匹配输出带.html结尾的URL实战例子:使用pyspider匹配输出带.html结尾的URL:@config(a ...

随机推荐

  1. JAVA学习笔记--迭代器

    迭代器(Iterator)是一种设计模式.它是一个对象,它的工作是遍历并选择序列中的对象,而客户端程序员不必知道或关心该序列底层的结构.创建迭代器的代价小,因而迭代器通常被称为轻量级对象. 一.Ite ...

  2. eclipse提示找不到dubbo.xsb报错

    需要下载一个dubbo.xsb文件到本地,并在eclipse中配置 下载路径:下载链接 下载方法: a).带开链接 b).点击[Raw]按钮 c). 右键->另存为 在eclipse中配置xsb ...

  3. Leetcode_2. Add_Two_Number

    2. Add_Two_Number 用两个非空链表分别表示两个非负整数,链表的节点表示数字的位,链表头表示数字的低位,链表尾表示数字高位.求两个链表所表示数字的和. 比如: Input: (2 -&g ...

  4. [T-ARA][HUE]

    歌词来源:http://music.163.com/#/song?id=22704406 wa du seu mo geum to yo do ga tae 어딜가도 스페셜한게 없어 [eo-dil ...

  5. [Linux] Migrate plugins and setting for vim

    Hot to migrate plugins and setting for vim from one computer to another ? Just copy  ~/.vim and ~/.v ...

  6. HDU 5646 DZY Loves Partition

    题目链接: hdu:http://acm.hdu.edu.cn/showproblem.php?pid=5646 bc:http://bestcoder.hdu.edu.cn/contests/con ...

  7. C语言文法翻译

    <程序>→<外部声明>|<程序><外部声明> <外部声明>→<函数定义>|<声明> <函数定义>→< ...

  8. PDO笔记

    <?php/* * 查询操作主要是PDO::query().PDO::exec().PDO::prepare().PDO::query()主要是用于有记录结果返回的操作,特别是SELECT操作, ...

  9. 使用vue的mixins混入实现对正在编辑的页面离开时提示

    mixins.ts import { Vue, Component, Watch } from "vue-property-decorator" Component.registe ...

  10. Linux架设DDNS服务器之自动更新脚本

    问题描述:客户端是动态IP,每次连网之后要nsupdate下才可以把客户端的hostname 与IP映射更新到DNS Server上 命令如下: nsupdate -k K*****.key > ...