zoukankan      html  css  js  c++  java
  • python类库31[读写文件]


    一 Open 函数

    open(path [,mode [,buffersize]])

    1)path文件的路径。

    2)mode文件的读写模式。

    r读打开存在的文件,

    w写打开文件,如果文件存在以前的内容被覆盖,如果文件不存在则创建之,

    a打开存在的文件添加新内容,

    r+读写打开文件,以前的被人被保留,

    w+读写打开文件,以前的内容被覆盖,

    a+读写打开文件,以前的被人被保留,

    b与rwa之一配合使用,表示以二进制打开,

    u与rwa之一配合使用,Applies the "universal" newline translator to the file as it is opened.

    3)buffersize指定访问文件时的buffer模式。

    0表示不使用buffer,

    1表示行buffer,

    其他的正整数表示buffer的大小,

    当忽略或为负数时使用默认的buffersize。


    二 实例

    outPath = "text.txt"
    inPath 
    = outPath
    print('---------------------------------')
    #Open a file for writing
    file = open(outPath, 'w')
    if file:
        file.write(
    'hello\ntom\n')
        file.writelines(
    'bye!')
        file.close()
    else:
        
    print ("Error Opening File.")
        
    print('---------------------------------')
    #Open a file for reading
    file = open(inPath, 'r')
    if file:
        
    print(file.read())
        
    #print(file.readlines())
        file.close()
    else:
        
    print ("Error Opening File.")

    print('---------------------------------')
    # read line from file
    import linecache
    filePath 
    = "text.txt"

    print (linecache.getline(filePath, 1))
    print (linecache.getline(filePath, 3))
    linecache.clearcache()

    print('---------------------------------')
    # read word from file
    filePath = "input.txt"
    wordList 
    = []
    wordCount 
    = 0

    #Read lines into a list
    file = open(filePath, 'rU')
    for line in file:
        
    for word in line.split():
            wordList.append(word)
            wordCount 
    += 1
    print (wordList)
    print ("Total words = %d" % wordCount)

    print('---------------------------------')
    # count line of file
    filePath = "input.txt"
    lineCount 
    = len(open(filePath, 'rU').readlines())
    print ("File %s has %d lines." % (filePath,lineCount))


    完!


    作者:iTech
    微信公众号: cicdops
    出处:http://itech.cnblogs.com/
    github:https://github.com/cicdops/cicdops

  • 相关阅读:
    2017-09-13
    JavaSE07——异常
    FastDFS入门、搭建以及应用(转载)
    Centos7安装JDK1.8
    「扫盲」 Elasticsearch(转载)
    Java06——面向对象
    Java05——数组
    Java02——基础
    spring boot 配置文件配置项 数字特殊处理问题
    java动态代理机制之自定义实现动态代理
  • 原文地址:https://www.cnblogs.com/itech/p/1625186.html
Copyright © 2011-2022 走看看