码迷,mamicode.com
首页 > 编程语言 > 详细

Python 文件I/O

时间:2016-11-17 20:21:42      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:name   print   简单   str   utf-8   live   写入   open   二进制   

文件I/O是Python中最重要的技术之一,在Python中对文件进行I/O操作是非常简单的。

1.打开文件

语法:

open(name[, mode[, buffering]])

1.1文件模式

1 r                 读模式
2 w                 写模式
3 a                 追加模式
4 b                 二进制模式(可添加到其他模式使用)
5 +                 读/写模式(可添加其他模式使用)

1.2缓冲区

open 函数的第三个参数( buffering ),表示文件的缓冲,当缓冲区大于0时(等于0时无缓冲,所有的读写操作都直接针对硬盘),Python会将文件内容存放到缓冲区(内存中),从而是程序运行的的更快,这时,只有使用 flush 或者 close 时才会将缓冲区中的数据更新到硬盘中。

2.文件的读写

2.1写入文件

#!/usr/bin/python
#-*- coding:UTF-8 -*-
#打开文件
f = open(rD:\python\File\Pra_1.txt,w)

try :
     #写入文件
     f.write(My name is OLIVER)

finally:
     #关闭文件
      f.close()

2.2读取文件

#!/usr/bin/python
#-*- coding:UTF-8 -*-
f = open(rD:\python\File\Pra_1.txt,r)
print(f.read())
f.close()

技术分享

3.文件特殊读取

3.1遍历每个字符,一次读取

方法一:

#!/usr/bin/python
#-*- coding:UTF-8 -*-
f = open(rD:\python\File\Pra_1.txt,r)

char = f.read(1)
while char:
    print(char)
    char = f.read(1)
f.close()

方法二:

#!/usr/bin/python
#-*- coding:UTF-8 -*-
f = open(rD:\python\File\Pra_1.txt,r)
while True:
    line = f.read(1)
    if not line:break
    print(line)
f.close()

技术分享

3.2遍历每一行读取

Pra_2.txt文件内容:

技术分享

 

#!/usr/bin/python
#-*- coding:UTF-8 -*-
f = open(rD:\python\File\Pra_2.txt,r)

while True:
    line = f.readline()
    if not line:break
    print(line)
f.close()

 读取结果:

技术分享

 

Python 文件I/O

标签:name   print   简单   str   utf-8   live   写入   open   二进制   

原文地址:http://www.cnblogs.com/OliverQin/p/6074677.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!