• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell
您的位置:首页 > 脚本语言 >python > python文件写入实例分析

python文件写入实例分析

作者: 字体:[增加 减小] 来源:互联网

通过本文主要向大家介绍了python脚本编写实例,python项目实例,python开发实例,python开发网站实例,python web开发实例等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com

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

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

f=file("hello.txt","w+")
li=["hello world\n","hello china\n"]
f.writelines(li)
f.close()
</div>

文件的内容:

hello world
hello china
</div>

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

f=file("hello.txt","a+")
new_context="goodbye"
f.write(new_content)
f.close()
</div>

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

hello world
hello china
goodbye
</div>

实践:

>>> 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()
</div>

结果:

hello world
hello china
goodbyegoodbye
</div>

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

</div>

您可能想查找下面的文章:

  • python脚本爬取字体文件的实现方法
  • Python只用40行代码编写的计算器实例
  • Python实现脚本锁功能(同时只能执行一个脚本)
  • python脚本爬取字体文件的实现方法
  • python获取当前运行函数名称的方法实例代码
  • Python类的动态修改的实例方法
  • Python中动态创建类实例的方法
  • Python自动发邮件脚本
  • Python类的动态修改的实例方法
  • Python中动态创建类实例的方法

相关文章

  • Python标准库os.path包、glob包使用实例
  • python实现斐波那契递归函数的方法
  • 安装Python的web.py框架并从hello world开始编程
  • python抓取网页内容示例分享
  • Python的Socket编程过程中实现UDP端口复用的实例分享
  • TensorFlow——Checkpoint为模型添加检查点的实例
  • Python画图学习入门教程
  • pymongo为mongodb数据库添加索引的方法
  • python中set常用操作汇总
  • Python多线程结合队列下载百度音乐的方法

文章分类

  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell

最近更新的内容

    • Python实现将xml导入至excel
    • Python、Javascript中的闭包比较
    • 用ReactJS和Python的Flask框架编写留言板的代码示例
    • Python生成随机密码
    • Python利用Beautiful Soup模块搜索内容详解
    • Python数据类型详解(一)字符串
    • Python中endswith()函数的基本使用
    • 以Flask为例讲解Python的框架的使用方法
    • python中的函数用法入门教程
    • python连接MySQL数据库实例分析

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有