文件读写

来源:互联网 发布:中国木制品数据 编辑:程序博客网 时间:2024/06/07 06:35

python文件读写的函数是open或者file
file_hander = open(filename, mode)
filename可以是文件,也可以是文件的绝对路径。

读取文件和遍历文件:read()、readline()、readlines()

#!/usr/bin/python#coding:utf8#open函数返回一个迭代类型的变量f_handler = open('/tmp/hello.txt')for line in f_handler:    print(line),f_handler.close()

也可以用下面的方法来读取和遍历文件

#!/usr/bin/python#coding:utf8# methord 1fo_handler = open("/tmp/hello.txt", "r")fr = fo_handler.read() #把所有的内容读为一行print fr,fo_handler.close()print "#1"*30#methord 2fo_handler = open("/tmp/hello.txt", "r")#readlines() #所有的内容生成一个list,每行为list的一个元素lines = fo_handler.readlines()for line in lines:    print line,  #line末尾已经有换行符了,因此加上逗号fo_handler.close()print "#2"*30#methord 3.1fo_handler = open("/tmp/hello.txt", "r")line = fo_handler.readline()while True:    print line.strip("\n") #去除末尾的换行符,要不然加上print会有两个换行符    line = fo_handler.readline()    if not line:        breakfo_handler.close()print "#3"*30#methord 3.2 readline()遍历文件的第二个方法是什么呢?暂时还没有想到fo_handler = open("/tmp/hello.txt", "r")while True:    line = fo_handler.readline()    if line:        print line,    else:        breakfo_handler.close()print "#3.2"*30#生成结果1 hello world2 hello world3 hello world4 hello world5 hello world#1#1#1#1#1#1#1#1#1#1#1#1#1#1#1#1#1#1#1#1#1#1#1#1#1#1#1#1#1#11 hello world2 hello world3 hello world4 hello world5 hello world#2#2#2#2#2#2#2#2#2#2#2#2#2#2#2#2#2#2#2#2#2#2#2#2#2#2#2#2#2#21 hello world2 hello world3 hello world4 hello world5 hello world#3#3#3#3#3#3#3#3#3#3#3#3#3#3#3#3#3#3#3#3#3#3#3#3#3#3#3#3#3#31 hello world2 hello world3 hello world4 hello world5 hello world#3.2#3.2#3.2#3.2#3.2#3.2#3.2#3.2#3.2#3.2#3.2#3.2#3.2#3.2#3.2#3.2#3.2#3.2#3.2#3.2#3.2#3.2#3.2#3.2#3.2#3.2#3.2#3.2#3.2#3.2

mode模式

r+与w+的区别
r+ 可读可写,若文件不存在,报错。写入是在文件的开头写入,替换掉相同数量的写入的字符。与其说是写入,不如说是文件开始处替换。

w+ 可读可写,若文件不存在,创建 文件,写入时先清空原文件,相当于linux shell中的 > 符号

a + 可读可写, 若文件不存在,创建 文件,在文件的末尾追加新的内容,相当于linux shell中的 >> 符号
这里写图片描述

0 0