欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python讀取文件指定行內(nèi)容實(shí)例講解

 更新時(shí)間:2020年03月02日 08:46:39   作者:阿布gogo  
在本篇文章里小編給大家整理的是關(guān)于python讀取文件指定行內(nèi)容實(shí)例講解,需要的朋友們可以參考下。

python讀取文件指定行內(nèi)容

import linecache
text=linecache.getline(r'C:\Users\Administrator\Desktop\SourceCodeofMongoRedis\chapter_5\generate_string.py',10)
第十行內(nèi)容為# info = '''1000001 王小小'''

實(shí)例擴(kuò)展:

本文實(shí)例講述了Python3實(shí)現(xiàn)從文件中讀取指定行的方法。分享給大家供大家參考。具體實(shí)現(xiàn)方法如下:

'''
'''
# Python的標(biāo)準(zhǔn)庫linecache模塊非常適合這個(gè)任務(wù)
import linecache
the_line = linecache.getline('d:/FreakOut.cpp', 222)
print (the_line)
# linecache讀取并緩存文件中所有的文本,
# 若文件很大,而只讀一行,則效率低下。
# 可顯示使用循環(huán), 注意enumerate從0開始計(jì)數(shù),而line_number從1開始
def getline(the_file_path, line_number):
 if line_number < 1:
 return ''
 for cur_line_number, line in enumerate(open(the_file_path, 'rU')):
 if cur_line_number == line_number-1:
  return line
 return ''
the_line = linecache.getline('d:/FreakOut.cpp', 222)
print (the_line)

還有一種方法

'''
'''
def loadDataSet(fileName, splitChar='\t'):
 """
 輸入:文件名
 輸出:數(shù)據(jù)集
 描述:從文件讀入數(shù)據(jù)集
 """
 dataSet = []
 with open(fileName) as fr:
  for line in fr.readlines()[6:]:
   curline = line.strip().split(splitChar)#字符串方法strip():返回去除兩側(cè)(不包括)內(nèi)部空格的字符串;字符串方法spilt:按照制定的字符將字符串分割成序列
   fltline = list(map(float, curline))#list函數(shù)將其他類型的序列轉(zhuǎn)換成字符串;map函數(shù)將序列curline中的每個(gè)元素都轉(zhuǎn)為浮點(diǎn)型
   dataSet.append(fltline)
 return dataSet

改變語句for line in fr.readlines()[6:]:可以指定讀取某幾行的內(nèi)容

到此這篇關(guān)于python讀取文件指定行內(nèi)容實(shí)例講解的文章就介紹到這了,更多相關(guān)python讀取文件指定行內(nèi)容內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論