(一)打开、读取文件

def open_file(filename):
    return open(filename, mode='r', encoding='utf-8', errors='ignore')


def read_file(filename):
    contents = []    # 存放文件内容
    with open_file(filename) as f:    # with语句,省去了‘关闭文件’的操作
        for each_line in f:    # for循环按行访问文件
            try:
                content = each_line.strip().split('\t')
                # S.strip([chars]) -> str:过滤每行首尾指定char字符,缺省过滤空格
                # S.split(sep=None, maxsplit=-1) -> list of strings:处理每行,可以按某个字符来分割行,返回list对象
                if content:
                    contents.append(content)
            except IOError:
                pass
            # 发生异常时的操作,自己随意,如print('Error:can't not read')
            # pass就直接不处理
    return contents


text = read_file('test1.txt')
print(text)


小记

1.strip()和split()函数要依据文本实际情况,灵活使用

2.打开模式mode参数要注意一下

3. 编码标准也要注意

4.with语句的使用注意一下

5.list的常用方法

6.注意打开、读取文件中可能出现的异常与处理

猜你喜欢

转载自blog.csdn.net/HaiYang_Gao/article/details/83242829