Head First Python笔记(第三章)

文本处理

  1. 读取文本
the_file=opne('sketch.txt')
#pass
the_file.close()
  1. 遍历文本
the_file=opne('sketch.txt')
for the_line in the_file:
    print(the_line)
the_file.close()
  1. 分割字符串
#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

  1. 异常处理
line ="man : yes we can!"
try:
  (role, spoken)=line.split(':')
  print(role,end='')
  print(" said: ",end='')
  print(spoken,end='')
except:
  pass
  1. 判断文件是否存在
import os

if os.path.exist('sketch.txt'):
    # to do
else:
  print("the file is missing!")
  1. 特定指定异常
try:
  data=open('sketch.txt')
  for item in data:
    try:
      # to do
    except ValueError:
      pass
except IOError:
  pass

你可能感兴趣的:(Head First Python笔记(第三章))