文件的增删改查操作

文件名:file11 2 3one two three一 二 三1、查看文件内容

f = open('file1','r',encoding='utf-8') #打开文件句柄for line in f: #循环文件句柄内容 print(line.strip()) #打印每一行f.close() #关闭文件#结果:1 2 3one two three一 二 三#备注:以下此种方法,会自动关闭文件with open('file1','r',encoding='utf-8') as f: for line in f: print(line.strip())2、往一个文件里追加内容

f = open('file1','a',encoding='utf-8')f.write('追加一个新的内容!!!\n')f.close()#结果:1 2 3one two three一 二 三追加一个新的内容!!!3、创建一个新的文件,并写入内容

f = open('file2','w',encoding='utf-8')f.write('4 5 6\n')f.write('四 五 六\n')f.close()#结果:file24 5 6四 五 六4、文件的字符内容修改

1、把文件file1的内容一二三的内容改为四五六

f = open('file1','r',encoding='utf-8')f_new = open('fil1.bak','w',encoding='utf-8')for line in f: if "一 二 三" in line: line = line.replace("一 二 三","四 五 六") f_new.write(line)f.close()f_new.close()

备注:使用的方法为一边读原文件,一边把原文件的内容写到一个新的文件,同时修改要改的字符