这一系列博客仅用于记录自己在学习python过程中的一些知识点。

将文件以行分割读取成数组形式

代码如下:

#!/usr/bin/env python
# -*- coding:UTF-8 -*-
# Python Version 2.7.5

# 函数用途:将文件以行分割读取成数组形式
# 参数:FILENAME: str。非空字符串。文件全路径。例如:/var/log/a.txt
# 返回值:LINES_ARR: list。数组。将文件按行分割,保存在数组里。

def ReadFileToArray(FILENAME):
    FILE_TMP = open(FILENAME, "r")
    LINES_ARR = []
    for LINE in FILE_TMP:
        LINES_ARR.append(LINE)
    FILE_TMP.close()
    return LINES_ARR

if __name__ == '__main__':
    FILEA = "/root/filea.txt"
    FILEA_ARR = ReadFileToArray(FILEA)
    print ("FILEA_ARR[0] is " + FILEA_ARR[0])
    print ("FILEA_ARR[1] is " + FILEA_ARR[1])
    print ("FILEA_ARR[2] is " + FILEA_ARR[2])

执行结果:

[root@LvZS-CentOS7 ~]# cat filea.txt 
This is the first line
This is the second line
This is the third line
[root@LvZS-CentOS7 ~]# 
[root@LvZS-CentOS7 ~]# 
[root@LvZS-CentOS7 ~]# python FileToArray.py 
FILEA_ARR[0] is This is the first line

FILEA_ARR[1] is This is the second line

FILEA_ARR[2] is This is the third line

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐