文本處理
- 讀取文本
the_file=opne('sketch.txt')
#pass
the_file.close()
- 遍歷文本
the_file=opne('sketch.txt')
for the_line in the_file:
print(the_line)
the_file.close()
- 分割字符串
#1. 正常處理
line ="man : yes we can!"
(role, spoken)=line.split(':')
print(role,end='')
print(" said: ",end='')
print(spoken,end='')
#2. 處理多個分割符出現(xiàn)異常
line ="man : yes we can! :nice"
(role, spoken)=line.split(':',1)
# man
# yes we can! :nice
#3. 分隔符不存在
line ="man, yes we can! "
##先判斷是否存在分隔符
if not line.find(':')==1:
##do something
- 異常處理
line ="man : yes we can!"
try:
(role, spoken)=line.split(':')
print(role,end='')
print(" said: ",end='')
print(spoken,end='')
except:
pass
- 判斷文件是否存在
import os
if os.path.exist('sketch.txt'):
# to do
else:
print("the file is missing!")
- 特定指定異常
try:
data=open('sketch.txt')
for item in data:
try:
# to do
except ValueError:
pass
except IOError:
pass