>>> 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进行文件操作的例子,包括如何打开文件并以写模式写入内容,然后读取内容并修改其中的部分行。此外,还展示了如何将修改后的内容再次写入文件。
352





