• Python学习日记(七) 文件操作


    文件操作:

    首先要有一个文件作为对象,例‘文件名’.txt

    1.文件路径:例 d:文件名.txt

    <1>:绝对路径:从根目录往后的路径

    <2>:相对路径:当前目录下的路径有什么算什么

    2.编码方式:UTF-8、GBK2312等

    3.操作模式:只读、只写、追加、写读、读写等

    文件是以什么变法方式储存就要以什么编码方式打开

    f = open('目标文件',mode='r',encoding='utf-8')  #以UTF-8编码的文件为例
    content = f.read()
    print(content)
    f.close()

    读:

    1.mode = 'r'文件的默认读取方式

    f.read() 文件打开后将bytes类型转化为str类型,返回值是str,Python3下的编码方式是unicode,

    f2 = open('f:目标文件.txt',mode='r',encoding='gbk')  #打开的文件编码是gbk
    content2 = f2.read()
    print(content2) #asd123文件
    f2.close()

    2.mode = 'rb'主要用于非文字类型文件操作,不用写编码方式

    3.先读后写

    f = open('目标文件',mode='r+',encoding='utf-8')
    print(f.read())                 #123456789
    f.write('abcd123')
    f.close()                       #123456789abcd123

    f.write()后添加一个print(f.read()) ,这段代码并不会执行

    在r+模式下进行写读,写了多少就会覆盖多少

    #原文件内容:123456789
    f = open('目标文件',mode='r+',encoding='utf-8')
    f.write('abcdefg')
    print(f.read())     #89
    f.close()

    4.mode = 'r+b' 以bytes类型打开

    #原文件内容:123456789
    f = open('目标文件',mode='r+b')
    print(f.read()) #b'123456789'
    f.write('abc'.encode('utf-8'))
    f.close()   #文件更新后:123456789abc 以utf-8编码

    写:

    在写入一个文件时若没有就会创建一个新的文件,有则将原文件删除再添加新的文件

    1.只读 mode = 'w'

    #原文件内容:123456789
    f = open('目标文件',mode='w',encoding='utf-8')
    f.write('abcdefg')
    f.close()   #文件更新后:abcdefg

    2.mode = 'wb'

    #原文件内容:123abc中国
    f = open('目标文件',mode='wb')
    f.write('gbka123'.encode('utf-8'))
    f.close()   #文件更新后:gbka123  编码方式:utf-8

    如果再以gbk编码方式去读取这个文件那么将报错

    3.mode = 'w+' 先写后读

    #原文件内容:123abc中国
    f = open('目标文件',mode='w+',encoding='utf-8')
    f.write('gbk2312')
    print(f.read())
    f.close()   #文件更新后:gbk2312  编码方式:utf-8

    4.mode = 'w+b' 

    f1 = open('logo-grey.png',mode='rb')
    content = f1.read()
    print(content)
    f1.close()
    f2 = open('logo-grey2.png',mode='wb')
    f2.write(content)
    f2.close()

    将原文件以rb形式读出来再写入到一个新的文件中去

    追加:

    1.mode = 'a'

    #原文件内容:123abc中国
    f = open('目标文件',mode='a',encoding='utf-8')
    f.write('%%%%')
    f.close()   #文件更新后:123abc中国%%%%  编码方式:utf-8

    2.mdoe = 'a+'

    #原文件内容:123abc中国
    f = open('目标文件',mode='a+',encoding='utf-8')
    f.write('%%%%')
    print(f.read())
    f.close()   #文件更新后:123abc中国%%%%  编码方式:utf-8

    其他功能:

    1.f.read(n)

      当文件打开的方式为文本模式时,代表读取n个字符

    #原文件内容:123abc中国
    f = open('目标文件',mode='r',encoding='utf-8')
    content = f.read(6)
    print(content)
    f.close()   #123abc 

      当文件打开为b模式时,代表读取n个字节

    f = open('logo-grey.png',mode='rb')
    content = f.read(10)
    print(content)
    f.close()   #b'x89PNG
    x1a
    x00x00'

    2.f.seek(光标位置)

    seek(n)光标移动到n位置,移动的单位为byte,所有utf-8编码的中文部分必须是3的倍数

    移动到开头:seek(0)

    移动到结尾:seek(0,2) seek最后一个参数表示从哪个位置进行偏移,1表示前位置,2表示结尾

    #原文件内容:123abc中国
    f = open('目标文件',mode='r+',encoding='utf-8')
    f.seek(0)       #将光标置于开头
    print(f.read())
    f.seek(0)       #将光标置于开头
    f.seek(0,2)     #将光标置于结尾
    print(f.read()) #读到空白
    f.seek(0)
    f.write('随便')   
    f.flush()       #文件更新后:随便中国 3*2 = 6 byte
    f.close()

    3.f.tell()

    告诉我们光标在什么位置

    #原文件内容:123abc中国
    f = open('目标文件',mode='r+',encoding='utf-8')
    f.seek(0)       #将光标置于开头
    print(f.tell()) #0
    print(f.read())
    f.seek(0)       #将光标置于开头
    print(f.tell()) #0
    f.seek(0,2)     #将光标置于结尾
    print(f.tell()) #12
    print(f.read()) #读到空白
    f.seek(0)
    print(f.tell())
    f.write('随便')
    f.flush()       #文件更新后:随便中国 3*2 = 6 byte
    print(f.tell()) #6
    f.close()

    4.f.readable()&f.writeable() 判断是否可读

    #原文件内容:123abc中国
    f = open('目标文件',mode='r+',encoding='utf-8')
    print(f.readable())
    print(f.writable())
    f.close()

    5.f.readline()

    每次只读一行,读取后的数据都有一个' ',原文件内容不会发生改变

    #原文件内容:  
    # 123
    # abc
    # gb2
    # 456
    # asd
    import os
    li = []
    f = open('目标文件',mode='r+',encoding='utf-8')
    while f.tell() != os.path.getsize('目标文件'):
        li.append(f.readline().strip())
    f.close()
    print(li)   #['123', 'abc', 'gb2', '456', 'asd']

    6.f.readlines()

    返回一个列表,列表中的元素是原文件的每一行,文件如果过大,占内存且容易崩盘

    #原文件内容:
    # 123
    # abc
    # gb2
    # 456
    # asd
    f = open('目标文件',mode='r+',encoding='utf-8')
    print(f.readlines())    #['123
    ', 'abc
    ', 'gb2
    ', '456
    ', 'asd']
    f.close()

    7.f.truncate()

    对原文件进行截取数据,0则全删 以byte为单位截取

    #原文件内容:123456abcd
    f = open('目标文件',mode='r+',encoding='utf-8')
    f.truncate(4)
    print(f.read()) #1234
    f.close()

    8.for循环

    文件句柄是一个迭代器,每一次的循环只在内存中占一行数据,非常节省内存

    #原文件内容:
    # 123
    # abc
    # gb2
    # 456
    # asd
    f = open('目标文件',mode='r+',encoding='utf-8')
    for i in f:
        print(i,end = '')
    f.close()
    # 打印内容
    # 123
    # abc
    # gb2
    # 456
    # asd

    9.修改文件

    # 原文件内容:
    # 123
    # abc
    # gb2
    # 456
    # asd
    # 123
    with open('目标文件',encoding='utf-8') as f1,open('目标文件.bak','w',encoding='utf-8') as f2:
        for line in f1:
            if '123' in line:
                line = line.replace('123','hello world!')
            f2.write(line)
    # 文件修改后内容:
    # hello world!
    # abc
    # gb2
    # 456
    # asd
    # hello world!
    import os
    os.remove('目标文件')                  #删除文件
    os.replace('目标文件.bak','目标文件')   #重命名

    10.文件打开的另一种办法

    with open('目标文件',mode='r',encoding='utf-8') as f:
        print(f.read())

    多个文件操作:

    with open('目标文件',mode='r',encoding='utf-8') as f1,
            open('目标文件2',mode='w',encoding='utf-8') as f2:
        print(f1.read())
        f2.write('something')
  • 相关阅读:
    Ruby单例方法和实例方法
    Silverlight本地化和全球化
    多线程 or 多进程 (转强力推荐)
    循环pthread_create导致虚拟内存上涨
    int在linux上的保存情况
    查看数据流的流程
    查看linux系统版本,内核,CPU,MEM,位数的相关命令(转)
    0/1背包问题
    linux下计算程序运行时间
    夸平台夸字符编码问题
  • 原文地址:https://www.cnblogs.com/Fantac/p/11280188.html
Copyright © 2020-2023  润新知