Python文件管理的中的读写文章简介

开发 后端
本文主要是介绍的是Python文件管理的介绍,读写文件的详细介绍,如果你对其感兴趣的话,你可以通过了解一下的文章,得到相关信息。

在计算机的应用的过程中,Python文件管理和别的计算机语言相比更为简单,如果你想了解Python文件管理怎样应用某些模块去进行文件的操作,你可以观看我们的文章希望你从中能得到相关的知识。

介绍

你玩过的游戏使用文件来保存存档;你下的订单保存在文件中;很明显,你早上写的报告也保存在文件中。

几乎以任何语言编写的众多应用程序中,文件管理是很重要的一部分。Python文件当然也不例外。在这篇文章中,我们将探究如何使用一些模块来操作文件。我们会完成读文件,写文件,加文件内容的操作,还有一些另类的用法。

读写文件

最基本的文件操作当然就是在文件中读写数据。这也是很容易掌握的。现在打开一个文件以进行写操作:

  1. view plaincopy to clipboardprint?  
  2. fileHandle = open ( 'test.txt', 'w' )   

 fileHandle = open ( 'test.txt', 'w' )‘w'是指文件将被写入数据,语句的其它部分很好理解。下一步就是将数据写入文件:

  1. view plaincopy to clipboardprint?  
  2. fileHandle.write ( 'This is a test.\nReally, it is.' )   
  3. fileHandle.write ( 'This is a test.\nReally, it is.' )  

这个语句将“This is a test.”写入文件的***行,“Really, it is.”写入文件的第二行。***,我们需要做清理工作,并且关闭Python文件管理:

  1. view plaincopy to clipboardprint?  
  2. fileHandle.close()   

fileHandle.close()正如你所见,在Python的面向对象机制下,这确实非常简单。需要注意的是,当你再次使用“w”方式在文件中写数据,所有原来的内容都会被删除。如果想保留原来的内容,可以使用“a”方式在文件中结尾附加数据:

  1. view plaincopy to clipboardprint?  
  2. fileHandle = open ( 'test.txt', 'a' )   
  3. fileHandle.write ( '\n\nBottom line.' )   
  4. fileHandle.close()   
  5. fileHandle = open ( 'test.txt', 'a' )  
  6. fileHandle.write ( '\n\nBottom line.' )  
  7. fileHandle.close()  

读写文件

  1. view plaincopy to clipboardprint?  
  2. fileHandle = open ( 'test.txt' )   
  3. print fileHandle.read()   
  4. fileHandle.close()   
  5. fileHandle = open ( 'test.txt' )  
  6. print fileHandle.read()  
  7. fileHandle.close()  

 以上语句将读取整个文件并显示其中的数据。我们也可以读取Python文件管理中的一行:

  1. view plaincopy to clipboardprint?  
  2. fileHandle = open ( 'test.txt' )   
  3. print fileHandle.rehttp://new.51cto.com/wuyou/adline() 
  4. # "This is a test."   
  5. fileHandle.close()   
  6. fileHandle = open ( 'test.txt' )  
  7. print fileHandle.readline() # "This is a test."  
  8. fileHandle.close()   

 以上就是对Python文件管理的介绍,望大家有所收获。

【编辑推荐】

  1. Python逻辑操作中的三大应用方案
  2. Python字符串在实际中的操作手册
  3. Python环境在进行初始化后的效果
  4. Python语言如何在C语言中实现操作
  5. Python编程语言如何保存搜索引擎结果
责任编辑:佚名 来源: 华军资讯
相关推荐

2021-05-27 09:01:14

Python文件读写Python基础

2020-07-06 15:50:41

Python文件Linux

2019-11-19 11:20:25

Python数据结构Windows

2017-08-01 17:34:47

Linux内核驱动文件读写

2021-08-05 10:00:02

Python编程语言

2010-03-23 17:53:46

Python递归文件

2019-12-19 16:22:38

程序员征文

2010-03-17 14:18:27

Python open

2021-02-26 20:55:56

JavaNIO随机

2010-01-06 11:24:27

Linux命令

2010-03-26 16:35:29

Python open

2010-11-19 11:22:25

oracle对系统文件

2010-02-24 10:49:11

Python运行环境

2010-11-19 10:57:43

Oracle读写文件

2010-01-22 16:21:50

C++ Builder

2009-12-17 16:55:03

OSPF路由协议

2010-03-19 15:16:11

Python代码

2010-03-19 11:18:07

Python读写配置文

2010-07-14 17:20:33

读写Perl文件

2020-11-05 08:56:19

Python
点赞
收藏

51CTO技术栈公众号