python文件读取

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

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.若是课程名称输入错误,会致使文件不存在,该怎么解决?less

#!/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()

 解决思路:分装函数(由于文件名称是外部输入,因此须要分装函数,相似于一个异常处理)函数

相关文章
相关标签/搜索