如何用python读取txt文件里指定行的内容,并导入excel?
怎么用python读取txt文件里指定行的内容,并导入excel??
f = open ('pit.txt','r')
print f.read() #读取文件里的所有内容
f.close()
如果我想读取第10行的数据,该怎么写。
另外,如果要将第10、11、12行的数据导入excel里,又该怎么写?
------解决方案--------------------
f = open ('pit.txt','r')
print f.read() #读取文件里的所有内容
f.close()
如果我想读取第10行的数据,该怎么写。
另外,如果要将第10、11、12行的数据导入excel里,又该怎么写?
------解决方案--------------------
- Python code
lnum = 0 with open('pit.txt', 'r') as fd: for line in fd: lnum += 1; if (lnum >= 10) && (lnum <= 13): print line fd.close()
------解决方案--------------------
- Python code
def eachlineof(filename): ''' 逐行读取给定的文本文件,返回行号、剔除末尾空字符的行内容 ''' with open(filename) as handle: for lno, line in enumerate(handle): yield lno+1, line.strip()
------解决方案--------------------
- Python code
import linecache print(linecache.getline(r'D:\z.txt',10))
------解决方案--------------------
如果文件不大,建议使用下面的方法。由于linecache会缓存,所以对大文件可以使用自己简单是实现getline如下:
- Python code
def getline(thefilepath, desired_line_number): if desired_line_number < 1: return '' for current_line_number, line in enumerate(open(thefilepath, 'rU')): if current_line_number == desired_line_number - 1 : return line return ''