python文件操作

  1. 读取文件内容
    import codecs
    #打开文件的几个步骤1.open文件 2.文件操作(读、写) 3.关闭文件
    f = codecs.open('1.txt')
    print (f.read())
    result = f.read()
    result = result.replace('1','A')
    print (result)
    print (type(result))
    print (dir(f))
    f.close()

  2. 写入一个新的文件
    import codecs
    #codecs这个模块主要用来解决文件乱码的问题,open(filename,mode)
    #mode有几个参数需要学习:r 读 w 写 b 二进制 a 追加
    f = codecs.open('2.txt','w')
    f.write("hello world!\n")
    f.write("hello 勇敢的心!\n")
    f.write("you are very very very cool!!!\n")
    f.write("we love 大湿兄 lessons!\n")
    f.close()

  3. With的特殊用法
    import codecs
    
    with codecs.open('1.txt','rb') as file:
        print (file.read())
        print (file.closed)
    print (file.closed)
    
    with codecs.open('1.txt','rb') as ff:
        for line,value in enumerate(ff):
            print (line,value)
            if line == 4-1:
                print (value)
    import linecache
    count =linecache.getline('1.txt',5)
    print (count)

  4. Codecs的特殊使用
    import codecs
    
    file = codecs.open('file3_2.txt','wb')
    print (dir(file))
    print (file.closed)
    file.write('hello world!\n北京欢迎您!\n')
    print file.tell()
    file.writelines(['aaaaaa\n','bbbbbb\n','dddddd\n'])
    file.seek(1)
    file.write('ccccc')
    print file.tell()
    print (file.encoding)
    print(file.mode)
    print (file.name)
    file.close()
    print (file.closed)

  5. 文件操作的常用方法
    
    
    
    
    
    
    import codecs
    # readlines()方法用来读取文件内容,文件内容的每一行都是一个字符串,最后返回一个list
    f = codecs.open('2.txt','rb')
    print (type(f))
    print (dir(f))
    text_list = f.readlines()
    print (text_list)
    print (type(text_list))
    print (text_list[0])
    print (f.readlines())
    f.close()
    #readline()方法读取文件一行内容,next()读取文件下一行内容,返回一个字符串 
    f = codecs.open('2.txt','rb')
    print f.readline()
    print f.readline()
    print f.readline()
    print f.readline()
    print f.next()
    f.close()
    # write()必须传入字符串,writelines()必须传入一个序列
    f = open('file3.txt','wb')
    f.write('hello world\n你好,what\'s you name\nhow old are you?\n')
    f.writelines(['你有女朋友了吗?\n','你有房有车吗?\n'])
    f.close()


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值