python文件写入实例分析

yipeiwu_com6年前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 使用 docopt 解析json参数文件过程讲解

Python 使用 docopt 解析json参数文件过程讲解

1. 背景 在深度学习的任务中,通常需要比较复杂的参数以及输入输出配置,比如需要不同的训练data,不同的模型,写入不同的log文件,输出到不同的文件夹以免混淆输出 常用的parser....

python修改操作系统时间的方法

本文实例讲述了python修改操作系统时间的方法。分享给大家供大家参考。具体实现方法如下: #-*- coding:utf-8 -*- import socket import st...

matplotlib作图添加表格实例代码

matplotlib作图添加表格实例代码

本文所示代码主要是通过Python+matplotlib实现作图,并且在图中添加表格的功能,具体如下。 代码 import matplotlib.pyplot as plt impo...

Python Collatz序列实现过程解析

编写一个名为 collatz()的函数,它有一个名为 number 的参数。如果参数是偶数,那么 collatz()就打印出 number // 2, 并返回该值。如果 number 是...

python清空命令行方式

python清空命令行 ! 有时我们在命令行上运行一些代码时,觉得有些冗余了,可以通过以下代码进行清除命令行上的代码。 import os def clear():os.system...