Python 专题四 文件基础知识


Posted in Python onMarch 20, 2017

前面讲述了函数、语句和字符串的基础知识,该篇文章主要讲述文件的基础知识(与其他语言非常类似).

一. 文件的基本操作

文件是指存储在外部介质(如磁盘)上数据的集合.文件的操作流程为:

打开文件(读方式\写方式)->读写文件(read\readline\readlines\write\writelines)->关闭文件

1.打开文件

调用函数open打开文件,其函数格式为:

file_obj=open(filename[, mode[, buffering]]) 返回一个文件对象(file object)

  — filename文件名(唯一强制参数)

    ·原始字符串 r'c:\temp\test.txt'

    ·转移字符串 'c:\\temp\\test.txt'

  — mode文件模式

    ·r 读模式

    ·w 写模式

    ·a 追加模式(写在上次后面)

    ·+ 读/写模式(没有文件即创建,可添加到其他模式中使用)

    ·b 二进制模式(可添加到其他模式中使用)

  — buffering缓冲(可选参数)

    ·参数=0或False 输入输出I/O是无缓冲的,所有读写操作针对硬盘

    ·参数=1或True 输入输出I/O是有缓冲的,内存替代硬盘

    ·参数>1数字代表缓冲区的大小,单位字节.-1或负数代表使用默认缓冲区大小

注意:当处理二进制文件如声音剪辑或图像时使用'b'二进制模式,可以'rb'读取一个二进制文件.

2.关闭文件

应该牢记使用close方法关闭文件,因为Python可能会缓存(出于效率考虑把数据临时存储某处)写入数据,如果程序突然崩溃,数据根本不会被写入文件,为安全起见,在使用完文件后关闭.如果想确保文件被关闭,应该使用try/finally语句,并且在finally子句中调用close方法.如:

#Open your file
  try:
    #Write data to your file
  finally:
   file.close()

3.读写文件

调用函数write方法向文件中写入数据,其函数格式为:

file_obj.write(string) 参数string会被追加到文件中已存部分后面

file_obj.writelines(sequence_of_strings) 仅传递一个参数,列表[ ] 元组() 字典{}

注意:实用字典时字符串的顺序出现是随机的.

#使用write()写文件 
file_obj=open('test.txt','w') 
str1='hello\n' 
str2='world\n' 
str3='python' 
file_obj.write(str1) 
file_obj.write(str2) 
file_obj.write(str3) 
file_obj.close() 
#使用writelines()写文件 
file_obj=open('test.txt','w') 
str1='hello\n' 
str2='world\n' 
str3='python' 
file_obj.writelines([str1,str2,str3]) 
file_obj.close() 
#输出 本地test.txt文件 
hello 
word 
python

调用函数read方法读取数据,其函数格式为:var=file_obj.read(),其中read全部读取,返回string;readline读取一行,返回string;readlines读取文件所有行,返回a list of string.例:

#使用read 
print 'Use the read' 
file_obj=open('test.txt','r') 
s=file_obj.read() 
print s 
file_obj.close 
#使用readline 
print 'Use the readline' 
file_obj=open('test.txt','r') 
line1=file_obj.readline() 
line1=line1.rstrip('\n') 
print 'l1 ',line1 
line2=file_obj.readline() 
line2=line2.rstrip('\n') 
print 'l2 ',line2 
line3=file_obj.readline() 
line3=line3.rstrip('\n') 
print 'l3 ',line3 
file_obj.close 
#使用readlines 
print 'Use the readlines' 
file_obj=open('test.txt','r') 
li=file_obj.readlines() 
print li 
file_obj.close

输出内容如下:

Use the read 
hello 
world 
python 
Use the readline 
l1 hello 
l2 world 
l3 python 
Use the readlines 
['hello\n', 'world\n', 'python']

可以发现在使用readline()函数时它返回的结果是'hello\n'字符串,需要使用rstrip去除'\n',否则print输出时总空一行.同时写入文件时使用格式化写入比较方便,如s="xxx%dyyy%s\n"%(28,'csdn').

#格式化写入 
fd=open('format.txt','w') 
head="%-8s%-10s%-10s\n"%('Id','Name','Record') 
fd.write(head) 
item1="%-8d%-10s%-10.2f\n"%(10001,'Eastmount',78.9) 
fd.write(item1) 
item2="%-8d%-10s%-10.2f\n"%(10002,'CSDN',89.1234) 
fd.write(item2) 
fd.close() 
#输出 
Id  Name  Record  
10001 Eastmount 78.90  
10002 CSDN  89.12

二. 文件与循环

前面介绍了文件的基本操作和使用方法,但是文件操作通常会与循环联系起来,下面介绍while循环和for循环实现文件操作.代码如下:

#使用while循环 
fr=open('test.txt','r') 
str=fr.readline() 
str=str.rstrip('\n') 
while str!="": 
 print str 
 str=fr.readline() 
 str=str.rstrip('\n') 
else: 
 print 'End While' 
fr.close 
#使用for循环 
rfile=open('test.txt','r') 
for s in rfile: 
 s=s.rstrip('\n') 
 print s 
print 'End for' 
rfile.close()

其中for调用迭代器iterator,迭代器提供一种方法顺序访问一个聚合对象中的各个元素,它相当于通过Iter函数获取对象的迭代器,再通过next函数(该方法调用时不需要任何参数)获取下一个值.for可以遍历iterator_obj包括List\String\Tuple\Dict\File.如:

s='www.csdn.NET'
  si=iter(s)   #生成迭代器
  print si.next() #调用next依次获取元素,最后迭代器没有返回值时引发StopIteration异常

三. 总结

该篇文章主要讲述了Python文件基础知识,包括文件的打开、读写、关闭操作、使用循环读写文件及迭代器的知识.希望对大家有所帮助,如果有错误或不足之处,还请海涵!

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持三水点靠木!

Python 相关文章推荐
Python中字典(dict)和列表(list)的排序方法实例
Jun 16 Python
Python 数据结构之队列的实现
Jan 22 Python
TensorFlow高效读取数据的方法示例
Feb 06 Python
利用python 更新ssh 远程代码 操作远程服务器的实现代码
Feb 08 Python
Python SQL查询并生成json文件操作示例
Aug 17 Python
python实现给scatter设置颜色渐变条colorbar的方法
Dec 13 Python
python虚拟环境迁移方法
Jan 03 Python
使用Python向C语言的链接库传递数组、结构体、指针类型的数据
Jan 29 Python
Python使用dict.fromkeys()快速生成一个字典示例
Apr 24 Python
Pyinstaller 打包发布经验总结
Jun 02 Python
Python将字典转换为XML的方法
Aug 01 Python
Python识别花卉种类鉴定网络热门植物并自动整理分类
Apr 08 Python
python 与GO中操作slice,list的方式实例代码
Mar 20 #Python
Python闭包的两个注意事项(推荐)
Mar 20 #Python
使用python实现生成用户信息
Mar 20 #Python
Unicode和Python的中文处理
Mar 19 #Python
Android 兼容性问题:java.lang.UnsupportedOperationException解决办法
Mar 19 #Python
Python 专题三 字符串的基础知识
Mar 19 #Python
关于python的bottle框架跨域请求报错问题的处理方法
Mar 19 #Python
You might like
PHP strtr() 函数使用说明
2008/11/21 PHP
php ajax 静态分页过程形式
2011/09/02 PHP
PHP大转盘中奖概率算法实例
2014/10/21 PHP
javascript知识点收藏
2007/02/22 Javascript
js的hasownproperty使用示例
2014/03/02 Javascript
js+jquery实现图片裁剪功能
2015/01/02 Javascript
javascript排序函数实现数字排序
2015/06/26 Javascript
js判断手机端(Android手机还是iPhone手机)
2015/07/22 Javascript
node.js使用cluster实现多进程
2016/03/17 Javascript
快速入门Vue
2016/12/19 Javascript
微信小程序--onShareAppMessage分享参数用处(页面分享)
2017/04/18 Javascript
浅谈JS中的常用选择器及属性、方法的调用
2017/07/28 Javascript
React中的render何时执行过程
2018/04/13 Javascript
简述vue路由打开一个新的窗口的方法
2018/11/29 Javascript
微信小程序分享功能onShareAppMessage(options)用法分析
2019/04/24 Javascript
简单了解Vue + ElementUI后台管理模板
2020/04/07 Javascript
Vue 实现创建全局组件,并且使用Vue.use() 载入方式
2020/08/11 Javascript
JavaScript实现滑块验证解锁
2021/01/07 Javascript
[32:36]完美世界DOTA2联赛PWL S3 LBZS vs CPG 第二场 12.12
2020/12/16 DOTA
python实现JAVA源代码从ANSI到UTF-8的批量转换方法
2015/08/10 Python
解决PyCharm import torch包失败的问题
2018/10/13 Python
详解python运行三种方式
2019/05/13 Python
Python在字符串中处理html和xml的方法
2020/07/31 Python
Linux系统下升级pip的完整步骤
2021/01/31 Python
CSS3 clip-path 用法介绍详解
2018/03/01 HTML / CSS
一款基于css3麻将筛子3D翻转特效的实例教程
2014/12/31 HTML / CSS
Oakley西班牙官方商店:太阳眼镜和男女运动服
2019/04/26 全球购物
怎么写好自荐信
2013/10/30 职场文书
土木工程专业推荐信
2014/02/19 职场文书
通用自荐信范文
2014/03/14 职场文书
春节联欢晚会主持词范文
2014/03/24 职场文书
环境科学专业求职信
2014/08/04 职场文书
拉贝日记观后感
2015/06/05 职场文书
2015年评职称个人工作总结
2015/10/15 职场文书
Nest.js参数校验和自定义返回数据格式详解
2021/03/29 Javascript
Python实现提取PDF简历信息并存入Excel
2022/04/02 Python