文本处理
- 读取文本
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. 处理多个分割符出现异常
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