# python的標準庫linecache模組非常適合這個任務
import linecache
the_line = linecache.getline(
'd:/freakout.cpp'
, 222)
print (the_line)
# linecache讀取並快取檔案中所有的文字,
# 若檔案很大,而唯讀一行,則效率低下。
# 可顯示使用迴圈, 注意enumerate從0開始計數,而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'
):
""
"
輸入:檔名
輸出:資料集
描述:從檔案讀入資料集
""
"
dataset =
with open(filename)
as
fr:
for
line
in
fr.readlines()[6:]:
curline = line.strip().split(splitchar)#字串方法strip():返回去除兩側(不包括)內部空格的字串;字串方法spilt:按照制定的字元將字串分割成序列
fltline = list(map(
float
, curline))#list函式將其他型別的序列轉換成字串;map函式將序列curline中的每個元素都轉為浮點型
return
dataset
python讀取檔案指定行
import linecache file open 3 2.txt r linecount len file.readlines linecache.getline 3 2.txt linecount 這樣做的過程中發現乙個問題,因為我的指令碼是迴圈讀取3 2.txt檔案,當3 2.txt發生變化...
讀取檔案指定行linecache
import linecache poem programming is fun when the work is done if you wanna make your work also fun use python f file poem.txt w f.write poem f.close ...
shell awk讀取檔案中的指定行的指定字段
awk指定讀取檔案中的某一行的某個字段 awk 可以設定條件來輸出檔案中m行到n行中每行的指定的k欄位,使用格式如下 awk nr m,nr n path filename m,n,k表示實在的數值。如果要用變數來表示m,n的值,則變數需要用單引號將其引起來。nr,是awk命令在此用法下的規定字段 ...