python文件写入实例分析

yipeiwu_com7年前Python基础

本文实例讲述了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程序设计有所帮助。

相关文章

Python的垃圾回收机制详解

引用计数 在Python源码中,每一个对象都是一个结构体表示,都有一个计数字段。 typedef struct_object { int ob_refcnt; struct...

python判断列表的连续数字范围并分块的方法

情况一:列表中的数字是连续数字(从小到大) from itertools import groupby lst = [1, 2, 3, 5, 6, 7, 8, 11, 12, 13...

python3人脸识别的两种方法

python3人脸识别的两种方法

本文实例为大家分享了python3实现人脸识别的具体代码,供大家参考,具体内容如下 第一种: import cv2 import numpy as np filename = 't...

Django 路由层URLconf的实现

分组 分组的目的:让服务端获得url中的具体数据,通过分组,把需要的数据按函数传参的方式传递给服务器后台 1-无名分组 若要从URL 中捕获一个值,只需要在它周围放置一对圆括号 #...

python编程使用selenium模拟登陆淘宝实例代码

selenium简介 selenium 是一个web的自动化测试工具,不少学习功能自动化的同学开始首选selenium ,相因为它相比QTP有诸多有点: * 免费,也不用再为破解Q...