zoukankan      html  css  js  c++  java
  • 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()
    

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

  • 相关阅读:
    python爬虫(二)_HTTP的请求和响应
    python迭代器
    矩阵快速幂
    hdu 2256 Problem of Precision
    牛客练习赛17 ABD
    hdu 1575 Tr A
    hdu 1757 矩阵快速幂
    51nod 1402最大值
    51nod 1393 0和1相等串
    勤奋的杨老师
  • 原文地址:https://www.cnblogs.com/general-seven/p/5893057.html
Copyright © 2011-2022 走看看