zoukankan      html  css  js  c++  java
  • python 文件操作

    以只读方式打开一个文件,如果文件不存在open()函数就会抛出一个IOError的错误        
    f = open('/Users/michael/test.txt', 'r')

    读取文件的全部内容,python把内容读到内存
    f.read()

    一行一行读取
    f.readline()

    f=open('login.py','r')
    for line in f:
        print line

    把所有行以列表的方式一次性读取
    f.readlines()

    一行一行读取大文件处理,python3已经去掉了
    f.xreadlines()

    查看指针位置
    f.tell()

    将指针移动到开头
    f.seek(0)

    关闭文件,文件使用完必须关闭。因为文件对象会占用操作系统的资源,并且操作系统同一时间能打开的文件数量也是有限的
    f.close()

    以写方式打开文件,如果文件不存在,则创建文件
    f = open('/Users/michael/test.txt', 'w')

    写入文件,如果文件有内容则覆盖。
    f.write('Hello, world!')


    关闭文件,将内容写入磁盘
    f.close()

    将内存中数据刷到硬盘
    f.flash()

    以追加方式打开文件,如果文件不存在,则创建文件
    f = open('/Users/michael/test.txt', 'a')
    从最后写入文件,如果文件有内容不会覆盖以前的内容。


    f.write('Hello, world!')
    关闭文件,将内容写入磁盘


    f.close()

    更改文件内容
    import fileinput
    for line in fileinput.input('/root/love.txt',inplace=1,backup='.bak'):
        line =line.replace('love','hate')
        print line,

    自动关闭打开文件    
    with open('test','r') as f:

      print(f.read)


  • 相关阅读:
    Leetcode 121. Best Time to Buy and Sell Stock
    Leetcode 120. Triangle
    Leetcode 26. Remove Duplicates from Sorted Array
    Leetcode 767. Reorganize String
    Leetcode 6. ZigZag Conversion
    KMP HDU 1686 Oulipo
    多重背包 HDU 2844 Coins
    Line belt 三分嵌套
    三分板子 zoj 3203
    二分板子 poj 3122 pie
  • 原文地址:https://www.cnblogs.com/sxlnnnn/p/6362947.html
Copyright © 2011-2022 走看看