python笔记我爱编程

Python IO编程

2018-08-09  本文已影响8人  weifeng_genius

1. 打开文件

f = open(filename,mode)

mode 功能
'r'
“w'
'a' 追加
'b' 二进制模式(添加到前三个模式中)除了纯文本外都应该用这个模式
'+' 读/写模式(添加到前三个模式种)
part = f.read(5000)    #一次读取5000字节
while part:
    print(part)
    part = f.read(5000)
with open(filename, 'rb') as f:
    for line in f:
        <do something with the line>

对可迭代对象 f,进行迭代遍历:for line in f,会自动地使用缓冲IO(buffered IO)以及内存管理,而不必担心任何大文件的问题。

with open(path,'r') as f:
    for line in f.readlines():
        print(line.strip())    # str.strip()用于去除结尾处的'\n'

2. 操作文件。

>> os.path.split('/Users/chen/testdir/file.txt')
('/Users/chen/testdir', 'file.txt')
>>> os.path.splitext('/path/to/file.txt')
('/path/to/file', '.txt')

3.序列化

JSON ——表示出来就是一个字符串,很方便读写。

JSON类型 Python类型
{} dict
[] list
"string" str
123.456 int or float
true/false True/False
null None
d = dict(name = 'Jane', age=20,score=88)
>> {'age': 20, 'name': 'bob', 'score': 88}
json.dumps(d)
>> '{"name": "bob", "age": 20, "score": 88}'
c = json.dumps(d)
json.loads(c)
>> {'age': 20, 'name': 'bob', 'score': 88}

然后再把 json.dumps(d) 通过文件读写的方式写在本地或者传输到别的地方去。

上一篇 下一篇

猜你喜欢

热点阅读