如下所示:
>>> f = open(r'E:\python\somefile.txt','w') 打开文件,写模式>>> f.write('this\nis no \nhailu') 写入三行话17>>> f.close()>>> f = open(r'E:\python\somefile.txt','r')>>> f.read()'this\nis no \nhailu' 查看一下>>> f = open(r'E:\python\somefile.txt')>>> lines = f.readlines() 把每一行的内容变为集合lines 的一个元素>>> f.close()>>> lines[1] = "isn't a\n" 给lines的第二个元素 重新赋值(改写了)>>> f = open(r'E:\python\somefile.txt','w')>>> f.writelines(lines)>>> f.close() >>改写后的文件打开就是这个样子
<pre name="code" class="python">thisisn't ahailu以上这篇python 读写文件,按行修改文件的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。