【python基础知识】对文本数据库的一些基本操作

有些测试功能不能将数据写入到数据库,因为服务器可能不会为此功能再创建数据表或修改原表,因此在测试期间用文件存储还是很有必要的,若直接移植到服务器中也不必新建数据库表。

本人小白一枚,只将查找到的资料应用后整理如下,既方便自己后续查询,也希望能帮助到小伙伴们。

-----------------------------------------------------------------------------------------------------

1、在文本文件的最上层添加数据

write_fileroute='文件路径'
with open(write_fileroute,'r+') as f:
    old=f.read()
    f.seek(0)
    f.write('new line\n'+old)

2、在文本文件最下层追加数据

write_fileroute="文件路径"
with open(write_fileroute,'a') as f:
f.write('.....\n')

3、从第几个文字开始覆盖(下面例子从第二个文字开始覆盖)

write_fileroute="文件路径"

with open(write_fileroute,'r+') as f:
    old=f.read()
    f.seek(2)
    f.write('2 new line?')

效果:


4、查询某行数据并更新

def alter(file,old_str,new_str):
    '''
    替换文件中的字符串
    :param file: 文件名
    :param old_str: 旧字符串
    :param new_str: 新字符串
    :return:
    '''
    file_data=''
    with open(file,'r') as f:
        for line in f:
            if old_str in line:
                line=line.replace(old_str,new_str)
            file_data+=line
    with open(file,'w') as f:
        f.write(file_data)
alter(文件路径,旧的字符串,新的字符串)
注意:若报utf-8编码错误,可尝试将以下代码中指定编码格式
with open(file,'r',encoding='utf-8)
with open(file,'w',encoding='utf-8)

猜你喜欢

转载自blog.csdn.net/qq_42152399/article/details/80936207