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

  • 相关阅读:
    cf1100 F. Ivan and Burgers
    cf 1033 D. Divisors
    LeetCode 17. 电话号码的字母组合
    LeetCode 491. 递增的子序列
    LeetCode 459.重复的子字符串
    LeetCode 504. 七进制数
    LeetCode 3.无重复字符的最长子串
    LeetCode 16.06. 最小差
    LeetCode 77. 组合
    LeetCode 611. 有效三角形个数
  • 原文地址:https://www.cnblogs.com/itech/p/1625186.html
Copyright © 2011-2022 走看看