zoukankan      html  css  js  c++  java
  • Python 学习笔记(二)文件操作

    Files

    • File iterators are best for reading lines
    • Content is strings, not objects
    • close is usually optional
    • Files are buffered and seekable.
    >>> myfile = open('myfile.txt', 'w') # Open for text output: create/empty
    >>> myfile.write('hello text file\n') # Write a line of text: string
    16  #length
    >>> myfile.write('goodbye text file\n')
    18
    >>> myfile.close() # Flush output buffers to disk
    >>> myfile = open('myfile.txt') # Open for text input: 'r' is default
    >>> myfile.readline() # Read the lines back
    'hello text file\n'
    >>> for line in open('myfile.txt'):
        print(line)
    
    
    hello text file
    
    goodbye text file

    File写入任意类型

    >>> X, Y, Z = 43, 44, 45 # Native Python objects
    >>> S = 'Spam' # Must be strings to store in file
    >>> D = {'a': 1, 'b': 2}
    >>> L = [1, 2, 3]
    >>>
    >>> F = open('datafile.txt', 'w') # Create output file
    >>> F.write(S + '\n') # Terminate lines with \n
    >>> F.write('%s,%s,%s\n' % (X, Y, Z)) # Convert numbers to strings
    >>> F.write(str(L) + '$' + str(D) + '\n') # Convert and separate with $
    >>> F.close()
    
    >>> chars = open('datafile.txt').read() # Raw string display
    >>> chars
    "Spam\n43,44,45\n[1, 2, 3]${'a': 1, 'b': 2}\n"
    >>> print(chars) # User-friendly display
    Spam
    43,44,45
    [1, 2, 3]${'a': 1, 'b': 2}
    >>> F = open('datafile.txt') # Open again
    >>> line = F.readline() # Read one line
    >>> line
    'Spam\n'
    >>> line.rstrip() # Remove end-of-line
    'Spam'
    >>> int(parts[1]) # Convert from string to int
    44
    >>> numbers = [int(P) for P in parts] # Convert all in list at once
    >>> numbers
    [43, 44, 45]
    >>> line = F.readline()
    >>> parts = line.split('$') >>> objects = [eval(P) for P in parts] # eval Convert to any object type >>> objects [[1, 2, 3], {'a': 1, 'b': 2}]

    按行遍历文件:

    with open('myfile.txt') as myfile:
        for line in myfile:
                print(line)

     Copy

    >>> L = [1,2,3]
    >>> D = {'a':1, 'b':2}
    
    >>> A = L[:] # Instead of A = L (or list(L))
    >>> B = D.copy() # Instead of B = D (ditto for sets)

    Two examples:

    - Change L will change M too

    >>> L = [1, 2, 3]
    >>> M = ['X', L, 'Y'] # Embed a reference to L
    >>> M
    ['X', [1, 2, 3], 'Y']
    >>> L[1] = 0 # Changes M too
    >>> M
    ['X', [1, 0, 3], 'Y']

    - Only change L, not M

    >>> L = [1, 2, 3]
    >>> M = ['X', L[:], 'Y'] # Embed a copy of L
    >>> L[1] = 0 # Changes only L, not M
    >>> L
    [1, 0, 3]
    >>> M
    ['X', [1, 2, 3], 'Y']

    比较相等

    • The == operator tests value equivalence.
    • The is operator tests object identity.
    •  Numbers are true if nonzero.
    • Other objects are true if nonempty.

    Python internally caches and reuses some strings as an optimization, there really is just a single string 'hello' in
    memory:

    >>> s1='hello'
    >>> s2='hello'
    >>> s1==s2
    True
    >>> s1 is s2
    True
    >>> s1='hello world'
    >>> s2='hello world'
    >>> s1 is s2
    False

    有意思的例子,注意嵌套的影响,tuple 与list 不同,tuple的Y与X 一样

    >>> L = [4, 5, 6]
    >>> X = L * 4 # Like [4, 5, 6] + [4, 5, 6] + ...
    >>> Y = [L] * 4 # [L] + [L] + ... = [L, L,...]
    >>> X
    [4, 5, 6, 4, 5, 6, 4, 5, 6, 4, 5, 6]
    >>> Y
    [[4, 5, 6], [4, 5, 6], [4, 5, 6], [4, 5, 6]]
    
    
    >>> L[1] = 0 # Impacts Y but not X
    >>> X
    [4, 5, 6, 4, 5, 6, 4, 5, 6, 4, 5, 6]
    >>> Y
    [[4, 0, 6], [4, 0, 6], [4, 0, 6], [4, 0, 6]]

    How to change tuple (4,5,6) to (1,5,6)

    >>> T = (4,5,6)
    >>> T = (1,) + T[1:]
    >>> T
    (1, 5, 6)

    换值

    >>> X='a'
    >>> Y='B'
    >>> X,Y = Y,X
    >>> X
    'B'

    赋值

    >>> a, *b = 'spam' #New method in 3.0
    >>> b
    ['p', 'a', 'm']
    >>> L = [1,2,3,4]
    >>> while L:
          f,*L=L  #f = L[0]
          print(f,L)
    
        
    1 [2, 3, 4]
    2 [3, 4]
    3 [4]
    4 []

    赋空值,需单独

    >>> a = b = []
    >>> b.append(42)
    >>> a, b
    ([42], [42])
    
    >>> a = []
    >>> b = []
    >>> b.append(42)
    >>> a, b
    ([], [42])
    >>> L = [1, 2]
    >>> L.append(3) # Append is an in-place change
    >>> L
    [1, 2, 3]
    
    >>> L = L.append(4) # But append returns None, not L
    >>> print(L) # So we lose our list!
    None

     

  • 相关阅读:
    【算法学习笔记】27.动态规划 解题报告 SJTU OJ 1254 传手绢
    【算法学习笔记】26.扫描维护法 解题报告 SJTU OJ 1133 数星星
    【算法学习笔记】25.贪心法 均分纸牌问题的分析
    【算法学习笔记】24.记忆化搜索 解题报告 SJTU OJ 1002 二哥种花生
    【算法学习笔记】23.动态规划 解题报告 SJTU OJ 1280 整装待发
    【算法学习笔记】22.算法设计初步 二分查找 上下界判断
    【算法学习笔记】21.算法设计初步 求第k个数 划分法 快排法
    【算法学习笔记】20.算法设计初步 归并排序 求逆序数
    【算法学习笔记】19.算法设计初步 最大子列和问题的几种方法
    【算法学习笔记】18.暴力求解法06 隐式图搜索2 八数码问题 未启发
  • 原文地址:https://www.cnblogs.com/zyf7630/p/3070618.html
Copyright © 2011-2022 走看看