欧2020

导航

python学习记录(五)-文件操作

open()参数说明

'''
参数1:路径  ./当前目录  ../上一级目录
参数2:
    基础模式:w r x a
        w:写入,不存在则创建,存在则打开,清空文件内容,光标指向最前面
        r:只读,不存在则报错,存在则打开,光标指向最前面
        x:异或,不存在则创建,存在则报错(防止覆盖),光标指向最前面
        a:追加,不存在则创建,存在则打开,不清空文件内容,光标指向最后面
    扩展模式:b +
        b:二进制
        +:增强(可读可写)
    文件操作模式组合:
        w,r,a,x,
        wb,rb,ab,xb,
        w+,r+,a+,x+,
        wb+,rb+,ab+,xb+
参数3:字符集,可选,二进制文件不需要设置
'''

写入文件

fp = open('./1.txt','w',encoding='utf-8')
fp.write('hello world')
fp.close()

读取文件

fp = open('./1.txt','r',encoding='utf-8')
print(fp.read()) # hello world
fp.close()

高级写法

with open('./1.txt','r+',encoding='utf-8') as fp:
    print(fp.read()) # hello world
    fp.write(' welcome')
    fp.seek(0) # 设置当前光标位置
    print(fp.read()) # hello world welcome

写入相关函数

vars1 = '123456'
vars2 = 12
var3 = ['ab','12']
var4 = [1,2,3,4]
with open('./1.txt','w',encoding='utf-8') as fp:
    fp.write(vars1) # 只能写入字符串
    #fp.write(vars2) TypeError: write() argument must be str, not int
    #fp.write(var3) TypeError: write() argument must be str, not list
    fp.writelines(var3) # 可以写入容器,容器内容只能是字符串
    #fp.writelines(var4) TypeError: write() argument must be str, not int

读取相关函数

with open('./1.txt','r+',encoding='utf-8') as fp:
    print(fp.read()) # 从头读到最后
    # 十月新番推荐:
    # 咒术回战
    # 炎炎消防队
    # 忧国的莫里亚蒂
    # 魔女之旅
    # 总之就是非常可爱
    fp.seek(0) # 设置指针位置 要考虑中文
    print(fp.read(8)) # 十月新番推荐:   指定读取字符位数,1个汉字算1个字符
    print(fp.readline()) # 咒术回战    读取一行
    print(fp.readline(2)) # 炎炎      读取一行的指定字符个数
    print(fp.readlines()) # 读取多行数据
    # ['消防队\n', '忧国的莫里亚蒂\n', '魔女之旅\n', '总之就是非常可爱']
    fp.seek(0)
    print(fp.readlines(5)) # 至少返回一行,位数不够一行时返回一行
    # ['十月新番推荐:\n']
    fp.seek(0,2) # 光标移到文件末尾
    fp.truncate(3) # 截断文件内容,从头开始截取指定字符位数保留下来,要考虑中文
    print(fp.tell()) # 返回光标所在位置

posted on 2020-12-20 09:55  欧2020  阅读(63)  评论(0编辑  收藏  举报