python文件写入实例分析
2015-04-08 11:20
671 查看
本文实例讲述了python文件写入的用法。分享给大家供大家参考。具体分析如下:
Python中wirte()方法把字符串写入文件,writelines()方法可以把列表中存储的内容写入文件。
f=file("hello.txt","w+") li=["hello world\n","hello china\n"] f.writelines(li) f.close()
文件的内容:
hello world hello china
write()和writelines()这两个方法在写入前会清除文件中原有的内容,再重新写入新的内容,相当于“覆盖”的方法。如果需要保留文件中原有的内容,只是需要追加新的内容,可以使用“a+”模式打开文件。
f=file("hello.txt","a+") new_context="goodbye" f.write(new_content) f.close()
此时hello.txt中的内容如下所示:
hello world hello china goodbye
实践:
>>> 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()
结果:
hello world hello china goodbyegoodbye
希望本文所述对大家的Python程序设计有所帮助。
您可能感兴趣的文章:
相关文章推荐
- Python3写入文件常用方法实例分析
- Python3写入文件常用方法实例分析
- python网络编程之文件下载实例分析
- Python3读取文件常用方法实例分析
- 使用Python和xlwt向Excel文件中写入中文的实例
- python中将正则过滤的内容输出写入到文件中的实例
- python文件操作之目录遍历实例分析
- python 小实例5 创建文件,并写入数据:要求不能与现存系统文件重名
- python读文件保存到字典,修改字典并写入新文件的实例
- 【python】pandas库pd.to_excel操作写入excel文件参数整理与实例
- python网络编程之文件下载实例分析
- python读写ini配置文件方法实例分析
- python 获取指定文件夹下所有文件名称并写入列表的实例
- Python学习--文件和存储器的写入和读出实例
- python解析xml文件实例分析
- python读写ini配置文件方法实例分析
- python 通过logging写入日志到文件和控制台的实例
- Python 文件操作技巧(File operation) 实例代码分析
- Python读csv文件去掉一列后再写入新的文件实例
- python解析xml文件实例分析