Python文件处理:打开、读、写、改、删、关闭

    科技2026-02-25  8

    在python中文件处理步骤有: 1.打开文件并创建对象; 2.对文件内容进行读取、写入、修改、删除等操作; 3.关闭并保存文件;

    1.打开文件并创建对象 通过open ()函数就可以打开文件并创建对象。 open(file[, mode=’r’[, buffering=-1]],encoding=[]) 各数的主要含义如下: (1) 参数file指定要打开或者创建的文件名称,如果该文件不存在当前目录,则需要明确指出绝对路径。 (2) 参数mode指定打开文件后的处理方式,其中包括:读模式、写模式、追加模式、二进制模式、文本模式、读写模式等。 (3) 参数buffering指定读写文件的缓冲模式,数值0表示不缓存,数值为1表示使用行缓存模式,大于1表示缓冲区的大小,默认值为-1,二进制文件和非交互文本文件以固定大小块为缓冲单位。 (4) 参数encoding指定对文本进行编码和解码的方式(乱码时可以加该参数调试)。 示例:

    >>> f = open('demo.txt','r')

    绝对路径打开方式

    >>> f = open('/Users/cnsolu/PycharmProjects/pythonProject/text.py','r')

    2.对文件内容进行读取、写入、修改、删除等操作; (1)读取 f = open(‘demo.txt’,‘r’) r:读模式(默认模式可以省略),如果文件不存在则抛出异常; +:读,写模式(可与其他模式组合使用) readable()函数判断是否可读

    >>> f.close <built-in method close of _io.TextIOWrapper object at 0x10d646a68> >>> f = open('/Users/cnsolu/PycharmProjects/pythonProject/text.py','r') >>> f.readable() True >>> f = open('/Users/cnsolu/PycharmProjects/pythonProject/text.py','w') >>> f.readable() False

    readline()函数读取一行内容

    >>> f = open('demo.txt','r') >>> f.readline() 'hello world! \n'

    readlines()函数把每行文本作为一个字符串存入列表,返回该列表;

    >>> f.readlines() ['hello world! \n', 'hello chwhello']

    read ()函数,读取所有内容

    f = open('demo.txt','r') >>> f.read() 'hello world! \nhello world! \nhello'

    read(x)函数,读取x个字符

    >>> f = open('demo.txt','r') >>> f.read(13) 'hello world! ' >>> f.read(5) '\nhell'

    拓展 for循环读文件内容

    >>> f = open('demo.txt','r') >>> for line in f: ... print(line) ... hello world! hello world! hello chwhello chw hello chw hello chw >>>

    (2)写入 f = open(‘demo.txt’,‘w’) w:写入模式,如果文件已经存在,先清空文件内容;如果文件不存在,则创建文件。 x:写入模式,创建新文件,如果文件已经存在则抛出异常; a:追加模式也是写入模式的一种,不覆盖文件的原始内容。 +:读,写模式(可与其他模式组合使用)

    writable(s) : 测试文件是否可写

    >>> f = open('demo.txt','a+') >>> f.writable() True >>> f.readable() True

    write(‘hello world’) : 将字符串hello world的内容写入文件

    >>> f.write('6666666') 7

    (3)修改 修改需求多种多样,这里就随便写两个。 替换文件中某个特定字符串: 例子为找出div字符串所在的行,延迟1秒打印出,将div修改bbb,并延时1秒打印出包含bbb的行。还可以用正则表达式的re.sub()函数。

    import time def alter(file,old_str,new_str): file_date= '' with open(file,'r') as f: for line in f: if old_str in line: time.sleep(1) print(line) line = line.replace(old_str,new_str) file_date +=line with open(file,'w') as f: f.write(file_date) alter('test2.py','div','bbb') with open('test2.py','r') as f: for line in f.readlines(): key = 'bbb' if key in line: time.sleep(1) print(line)

    末尾插入另一个文件内容:

    with open('main.py','r') as a: b = a.readlines() with open('test2.py','a') as f: f.writelines(b)

    (4)删除 删除某个字符串: 用上面修改方式中的替换,将目标字符串替换为空‘’。例子略。 清空文本:用w参数或者truncate()函数

    with open('test2.py','a') as f: f.truncate(0)

    3.关闭并保存文件; close()函数,关闭保存文件

    >>> f.close()

    关键字with能够自动管理资源,总能保证文件的自动正确关闭

    >>> with open('demo.txt','a') as f: ... f.write('999999') ... 6
    Processed: 0.019, SQL: 9