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