Python基础之八IO编程

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014360817/article/details/54844750
'''
    读文件
        要以读文件的模式打开一个文件对象,Python内置了读文件的函数,用法和C是兼容的

'''
f = open('/Users/gaocai/Desktop/Python/file.text', 'r')
print(f.read())#读文件
f.close()

try:
    f = open('/Users/gaocai/Desktop/Python/file.text', 'r')
    print(f.read())
finally:
    if f:
        f.close()

with open('/Users/gaocai/Desktop/Python/file.text', 'r') as f:#with语句自动调用close()方法
    print(f.read())

f = open('/Users/gaocai/Desktop/Python/file.text', 'r')
for line in f.readline():#按照行读
    print(line.strip())#把末尾的'\n'删掉
f.close()

f = open('/Users/gaocai/Desktop/Python/file.text', 'r', encoding='gbk', errors='igonre')

'''
    写文件
        写文件和读文件是一样的,唯一的区别是调用open()函数,传入的表示符'w'或者'wb'文本或者二进制

'''
f = open('/Users/gaocai/Desktop/Python/file.text', 'w')
f.write("Hello, World!")
f.close()

with open('/Users/gaocai/Desktop/Python/file.text', 'w') as f:
    f.write('阅读: 74292读写文件是最常见的IO操作。Python内置了读写文件的函数,用法和C是兼容的。')

'''
    StringIO和BytesIO

'''

'''
    StringIO
'''

from io import StringIO
f = StringIO()
print(f.write('hello'))#写入字符串
print(f.getvalue())#读取字符串

'''
    BytesIO
'''

from io import BytesIO
f = BytesIO()
print(f.write('你好'.encode('utf-8')))
print(f.getvalue())

'''
    操作文件和目录
'''
import os
print(os.name)#系统名
print(os.uname())#系统详细信息
print(os.environ)#环境变量
print(os.environ.get('PATH'))#获得某个环境变量的值
print(os.path.abspath('.'))#获取当前目录的绝对路径
print(os.path.join('/Users/gaocai/Desktop/Python', 'testdir'))#在某个目录下创建一个新目录,首先把新目录完整路径显示出来
#print(os.mkdir('/Users/gaocai/Desktop/Python2'))#创建一个目录
#print(os.rmdir('/Users/gaocai/Desktop/Python2'))#删掉一个目录

import pickle
d = dict(name = 'Bod', age = 20, score = 88)
pickle.dumps(d)#序列化一个对象
f = open('dump.txt', 'wb')
pickle.dump(d, f)#将这个对象保存到文件中
f.close()

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

'''
    JSON
'''
import json
d = dict(name='Bod', age=20, score=88)
json.dumps(d)

更多精彩内容访问个人站点www.gaocaishun.cn

猜你喜欢

转载自blog.csdn.net/u014360817/article/details/54844750
今日推荐