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提供了两个非常重要的功能来处理python程序在运行中出现的异常和错误。你可以使用该功能来调试python程序。 1.异常处理: 本站Python教程会具体介绍。 2.断言(...

python中Pycharm 输出中文或打印中文乱码现象的解决办法

python中Pycharm 输出中文或打印中文乱码现象的解决办法

1. 确保文件开头加上以下代码: # -*- coding:utf-8 -*- 还可以加上 import sys reload(sys) sys.setdefaulte...

python3 中的字符串(单引号、双引号、三引号)以及字符串与数字的运算

python3中的字符串是一种常见的数据类型。 字符串有多种表现形式:单引号、双引号和三引号,且这些字符串的表现形式(单、双、三)都必须是成对出现的。 单、双引号是英文的:‘'和"",三...

Python 正则表达式 re.match/re.search/re.sub的使用解析

From Python正则表达式 re.match(pattern, string, flags=0) 尝试从字符串起始位置匹配一个模式;如果不是起始位置匹配成功,则 re.match(...

浅谈Python数据类型之间的转换

Python数据类型之间的转换 函数 描述 int(x [,base])...