f = open(r'G:\2.txt')
print f.read()
f.close()
try:
t = open(r'G:\2.txt')
print t.read()
finally:
if t: t.close()
with open(r'G:\2.txt') as g:
for line in g:
print line
with 自動呼叫 close(),即使發生異常也能保證資源釋放,最簡潔安全。
Windows 路徑反斜線 \ 在字串中為跳脫字元:
>> f = 'g:\a.txt'
>>> print f
g: .txt # \a 被解讀為 BEL (ASCII 7)
r → r'G:\2.txt',不處理跳脫。'G:\\2.txt'。'G:/2.txt' (跨平台通用)。>> f = 'g:\a.txt'; print f
g: .txt
>>> f1 = 'g:\\a.txt'; print f1
g:\a.txt
>>> r'g:\a.txt'
'g:\\a.txt'
>>> 'g:\a.txt'
'g:\x07.txt' # \a = \x07
建議統一使用 r'path' 或正斜線,避免跳脫字元陷阱。