python文件读取

1.如何将一个“lessons.txt”文档一行行输出?

myfile = file(‘lessons.txt’)
 
for f in myfile.readlines():
    print f
 
myfile.close()
#-*- coding:utf-8 -*-
file_path = "C:\\Users\\Administrator\\workspace\\template.txt" 
 
with open(file_path,'r') as f:
    lines = f.readlines() #把整个文件全部读取到内存中,当作一个List 
    for line in lines:
    print line

 2.如果课程名称输入错误,会导致文件不存在,该怎么解决?

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
 
def get_file(file_path):
    # 验证文件路径是否存在
    # 通过路径返创建file对象
    # 返回file对象
    # xxxddfdvfv = file(file_path)
    assert isinstance(file_path, str)
    return file(file_path)
 
myfile = get_file('lessons.txt')
for f in myfile.readlines():
    print f
myfile.close()

 解决思路:分装函数(因为文件名称是外部输入,所以需要分装函数,类似于一个异常处理)

posted @ 2016-09-21 16:08  prime7  阅读(418)  评论(0编辑  收藏  举报