Python学習ノート(二)ファイル操作
16881 ワード
Files File iterators are best for reading lines Content is strings, not objects close is usually optional Files are buffered and seekable.
File書き込みの種類
ファイルを行単位で巡回するには、次の手順に従います.
Copy
Two examples:
- Change L will change M too
- Only change L, not M
比較的等しい 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' inmemory:
興味深い例は,ネストの影響に注意し,tupleはlistと異なり,tupleのYはXと同じである.
How to change tuple (4,5,6) to (1,5,6)
へんかん
に値を付ける
空の値を割り当てるには、個別の値が必要です.
>>> myfile = open('myfile.txt', 'w') # Open for text output: create/empty
>>> myfile.write('hello text file
') # Write a line of text: string
16 #length
>>> myfile.write('goodbye text file
')
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
'
>>> 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 + '
') # Terminate lines with
>>> F.write('%s,%s,%s
' % (X, Y, Z)) # Convert numbers to strings
>>> F.write(str(L) + '$' + str(D) + '
') # Convert and separate with $
>>> F.close()
>>> chars = open('datafile.txt').read() # Raw string display
>>> chars
"Spam
43,44,45
[1, 2, 3]${'a': 1, 'b': 2}
"
>>> 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
'
>>> 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']
比較的等しい
Python internally caches and reuses some strings as an optimization, there really is just a single string 'hello' inmemory:
>>> 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