文件读写

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 1
fo_handler = open("/tmp/hello.txt", "r")
fr = fo_handler.read() #把所有的内容读为一行
print fr,
fo_handler.close()
print "#1"*30

#methord 2
fo_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.1
fo_handler = open("/tmp/hello.txt", "r")
line = fo_handler.readline()
while True:
    print line.strip("\n") #去除末尾的换行符,要不然加上print会有两个换行符
    line = fo_handler.readline()
    if not line:
        break
fo_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:
        break
fo_handler.close()
print "#3.2"*30

#生成结果
1 hello world
2 hello world
3 hello world
4 hello world
5 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#1
1 hello world
2 hello world
3 hello world
4 hello world
5 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#2
1 hello world
2 hello world
3 hello world
4 hello world
5 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#3
1 hello world
2 hello world
3 hello world
4 hello world
5 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中的 >> 符号
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值