需要讀取的文件內(nèi)容:http://python.itcarlow.ie/chapter3/sketch.txt
1. 切換工作目錄
代碼:
import os
os.chdir('D:/') # 注意斜杠方向
print(os.getcwd())
輸出:
D:\
2. 打開文件open()
代碼:
try:
data = open('sketch.txt')
print(data.readline(), end='') # 讀取一行內(nèi)容
print(data.readline(), end='') # 讀取二行內(nèi)容
data.seek(0) # 返回文件起始位置
except IOError:
print('The data file is missing!')
輸出:
Man: Is this the right room for an argument?
Other Man: I've told you once.
0
3. 輸出所有內(nèi)容
代碼:
for each_line in data:
try:
(role, line_spoken) = each_line.split(':', 1)
print(role, end='')
print(' said: ', end='')
print(line_spoken, end='')
except ValueError: # 因?yàn)閿?shù)據(jù)中存在多個冒號和沒有冒號的數(shù)據(jù),需要處理產(chǎn)生的錯誤,
print(each_line)
部分輸出:
Man said: Is this the right room for an argument?
Other Man said: I've told you once.
... ...
Man said: (exasperated) Oh, this is futile!!
Other Man said: No it isn't!
Man said: Yes it is!
4. 關(guān)閉文件
代碼:
if 'data' in locals():
data.close()
# 或者使用with打開文件,則不需要手動close:
with open('sketch.txt', 'w') as data:
5. 完整代碼
try:
with open('sketch.txt') as data:
for each_line in data:
try:
(role, line_spoken) = each_line.split(':', 1) # split('', 1)處理多個冒號的情況,只分一次;
print(role, end='')
print(' said: ', end='')
print(line_spoken, end='')
except ValueError: # 因?yàn)閿?shù)據(jù)中存在沒有冒號的數(shù)據(jù),需要處理產(chǎn)生的錯誤;
print(each_line)
except IOError as err:
print('IOError: ' + str(err))