Python从文件中读取指定的行
如果想根据给出的行号, 从文本文件中读取一行数据, Python标准库linecache模块非常适合这个任务:
测试文件内容 :
This is line 1.
This is line 2.
This is line 3.
This is line 4.
This is line 5.
This is line 6.
This is line 7.
This is line 8.
测试代码:
>>> import linecache
编写了一个名为learning_python.txt的文件,内容如下:
[rootcentos7 tmp]# cat learning_python.txt
In Python you can code;
In Python you can learn object;
In Python you can learn class.
要求:编写一个程序,它读取这个文件并打印三次。
1、第一次打印时读取整个文件;
2、第二次打印时遍历文件对象;
3、第三次打印时将各行存储在一个列表中,再
如下所示:
import matplotlib.pyplot as plt
import numpy as np
def readfile(filename):
dataList = []
dataNum = 0
with open(filename,'r') as f:
for line in f.readlines():
linestr = line.strip('\n')
if len(linestr) 1:
dataList.append(float(li