Home > Backend Development > Python Tutorial > python文件写入实例分析

python文件写入实例分析

WBOY
Release: 2016-06-10 15:15:52
Original
1197 people have browsed it

本文实例讲述了python文件写入的用法。分享给大家供大家参考。具体分析如下:

Python中wirte()方法把字符串写入文件,writelines()方法可以把列表中存储的内容写入文件。

f=file("hello.txt","w+")
li=["hello world\n","hello china\n"]
f.writelines(li)
f.close()
Copy after login

文件的内容:

hello world
hello china
Copy after login

write()和writelines()这两个方法在写入前会清除文件中原有的内容,再重新写入新的内容,相当于“覆盖”的方法。如果需要保留文件中原有的内容,只是需要追加新的内容,可以使用“a+”模式打开文件。

f=file("hello.txt","a+")
new_context="goodbye"
f.write(new_content)
f.close()
Copy after login

此时hello.txt中的内容如下所示:

hello world
hello china
goodbye
Copy after login

实践:

>>> f=file("hello.txt","w+")
>>> li=["hello world\n","hello china\n"]
>>> f.writelines(li)
>>> f.close()
>>> 
>>> f=file("hello.txt","a+")
>>> new_context="goodbye"
>>> f.write(new_content)
>>> f.write(new_content)
>>> f.close()
Copy after login

结果:

hello world
hello china
goodbyegoodbye
Copy after login

希望本文所述对大家的Python程序设计有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template