您的位置:首页 > 编程语言 > Python开发

python 读写文件,按行修改文件

2016-09-12 18:02 405 查看
>>> 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">this
isn't a
hailu


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python