python文件读写

python 文件读写

文件操作模式:"r" 读;"w" 写;"a" 追加;"r+" 可读可写,文件若不存在就报错;"w+"可写可读,文件不存在就创建;"a+"可写可读,文件不存在则创建。对应的二进制文件操作模式:"rb", "wb", "ab", "rb+", "wb+", "ab+"

#!/usr/bin/env
#ecoding:utf-8

def read(input_file):
    """ read """
    try:
        f = open(input_file, "r")
        for line in f:
            # line has "\n"
            line = line.strip("\n").strip(" ").strip("\t")
            print line
        f.close()
    except Exception as e:
        print str(e)
        f.close()

def read2(input_file):
    """ read2 """
    try:
        with open(input_file, "r") as f:
            s = f.read()
            f.close()
            print s
    except Exception as e:
        print str(e)
        f.close()

def write(output_file):
    """ write """
    try:
        f = open(output_file, "w")
        f.write("one line\n")
        f.close()
    except Exception as e:
        print str(e)
        f.close()

def append(append_file):
    """ append """
    try:
        f = open(append_file, "a")
        f.write("append line\n")
        f.close()
    except Exception as e:
        print str(e)
        f.close()

if __name__ == "__main__":
    #read("./tmp")
    #read2("./tmp")
    #write("./tmp2")
    append("./tmp2")

 

file_obj.seek(offset,whence=0)

file_obj.seek(offset,whence=0)方法用来在文件中移动文件指针。offset表示偏移多少。可选参数whence表示从哪里开始偏移,默认是0为文件开头,1为当前位置,2为文件尾部。举例:

f = open("test1.txt", "a+")
print(f.read())
f.write('1')
f.seek(0, 0)# 把文件指针从末尾移到开头,没有这句话下面的read()就读不到正确的东西
print(f.read())
f.close()

注意:这个文件指针的改变只是作用于'r',对'w'和'a'不会起作用,如果是'w',那么write()永远都是从开头写(会覆盖后面对应位置的内容),是'a'的话write()就永远都是从最后开始追加。

字符编码

要读取非UTF-8编码的文本文件,需要给open()函数传入encoding参数,例如,读取GBK编码的文件:

>>> f = open('test.txt', 'r', encoding='gbk')
>>> f.read()
'测试'

遇到有些编码不规范的文件,你可能会遇到UnicodeDecodeError,因为在文本文件中可能夹杂了一些非法编码的字符。遇到这种情况,open()函数还接收一个errors参数,表示如果遇到编码错误后如何处理。最简单的方式是直接忽略:

>>> f = open('test.txt', 'r', encoding='gbk', errors='ignore')

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值