導航:首頁 > 編程語言 > python讀文件某一行

python讀文件某一行

發布時間:2023-01-07 20:37:34

Ⅰ 如何用python讀取文本中指定行的內容

#readsomelines.py
#!/usr/bin/envpython3
importsys

fname='aa.txt'


defmain():
lines=[iforiinsys.argv[1:]ifi.isdigit()]
withopen(fname)asf:
s=f.read().split(' ')
print('filename:{},total:{}lines.'.format(fname,len(s)))
foriinlines:
index=int(i)-1
content=s[index]ifindex<len(s)else''
print('line{}:{}'.format(i,content))


main()
$pythonreadsomelines.py23

file name: aa.txt, total: 5 lines.

line 2: (comment line)

line 3: (atom symbol) 1 1 1

Ⅱ 如何用python讀取文本中指定行的內容

1 利用python的readlines()函數:

[python] view plain
<strong><span style="font-size:24px;"> </span><span style="font-size:14px;">fobj = open(r'Ori.Data.txt','r')
for line in fobj.readlines()[1000:]
fobj.close()</span></strong>

2 利用 linecache

[python] view plain
<strong><span style="font-size:14px;"> import linecache
print(linecache.getline(r'D:\z.txt',10))</span></strong>

3 讀取10行到13行中的內容

[python] view plain
<span style="font-size:14px;"> <strong> lnum = 0
with open('pit.txt', 'r') as fd:
for line in fd:
lnum += 1;
if (lnum >= 10) && (lnum <= 13):
print line
fd.close()</strong></span>

4 求文本的行數

[python] view plain
<span style="font-size:14px;"><strong> fobj = open('Ori_Data.txt','r')
row_len = len(fobj.readlines()) </strong></span>
[python] view plain
<span style="font-size:14px;"><strong>
</strong></span>
[python] view plain
<span style="font-size:14px;"><strong> fobj = open(filepath,'r')
data = fobj.read()
fobj.close()
text_len = data.count('\n')<span style="font-family: Arial, Helvetica, sans-serif;"></span></strong></span>

Ⅲ python讀取csv文件的某一行

1.全部讀到成列表然後選取行(容易超時,亂碼等問題)
2.利用迭代工具,代碼如下:
from itertools import islice
with open('data.tsv', 'r') as f:
for line in islice(f, 1, None):
# process data
f.close()
修改islice函數中第2個參數n即可,表示讀到f文件對象的第n行

Ⅳ 如何用python讀取文本中指定行的內容

1.默認你知道「指定行」的行號
那麼:
defappoint_line(num,file):
withopen(file,"r",encoding='utf-8')asf:
out=f.readlines[num-1]
returnout
print(appoint_line(2,"c:/text.txt"))
以上示例為讀取c盤下的text.txt文件的第二行
2.假如所謂「指定行」為開頭幾個字元,這里假設為三個
defappoint_line(file):
#appoimt_spring是指你指定行的前三個字元,你可以自行指定
appoint_spring=input(">>").strip()
withopen(file,"r",encoding='utf-8')asf:
forlineinf.readlines():
ifline[0:3]==appoint_spring:
returnline
print(appoint_line("c:/text.txt"))
以上示例為根據你輸入的所指定行的前三個字元列印出c盤下的text.txt文件下的「指定行」

Ⅳ Python按行讀取文件的簡單實現方法

Python按行讀取文件的簡單實現方法
下面小編就為大家帶來一篇Python按行讀取文件的簡單實現方法。小編覺得挺不錯的,現在就分享給大家,也給大家做個參考。
1:readline()
file = open("sample.txt")
while 1:
line = file.readline()
if not line:
break
pass # do something
file.close()
一行一行得從文件讀數據,顯然比較慢;
不過很省內存;
測試讀10M的sample.txt文件,每秒大約讀32000行;
2:fileinput
import fileinput
for line in fileinput.input("sample.txt"):
pass
寫法簡單一些,不過測試以後發現每秒只能讀13000行數據,效率比上一種方法慢了兩倍多;
3:readlines()

file = open("sample.txt")
while 1:
lines = file.readlines(100000)
if not lines:
break
for line in lines:
pass # do something
file.close()
用同樣的數據測試,它每秒可以讀96900行數據!效率是第一種方法的3倍,第二種方法的7倍!
4:文件迭代器
每次只讀取和顯示一行,讀取大文件時應該這樣:
file = open("sample.txt")
for line in file:
pass # do something
file.close()
以上就是小編為大家帶來的Python按行讀取文件的簡單實現方法全部內容了

Ⅵ python如何隨機讀取一行

#!/usr/bin/envpython
#coding:utf-8

defgetfilelines(filename,eol=' ',buffsize=4096):
"""計算給定文件有多少行"""
withopen(filename,'rb')ashandle:
linenum=0
buffer=handle.read(buffsize)
whilebuffer:
linenum+=buffer.count(eol)
buffer=handle.read(buffsize)
returnlinenum


defreadtline(filename,lineno,eol=" ",buffsize=4096):
"""讀取文件的指定行"""
withopen(filename,'rb')ashandle:
readedlines=0
buffer=handle.read(buffsize)
whilebuffer:
thisblock=buffer.count(eol)
ifreadedlines<lineno<readedlines+thisblock:
#inthisblock:findthelinecontent,andreturnit
returnbuffer.split(eol)[lineno-readedlines-1]
eliflineno==readedlines+thisblock:
#needcontinuereadlinerestpart
part0=buffer.split(eol)[-1]
buffer=handle.read(buffsize)
part1=buffer.split(eol)[0]
returnpart0+part1
readedlines+=thisblock
buffer=handle.read(buffsize)
else:
raiseIndexError


defgetrandomline(filename):
"""讀取文件的任意一行"""
importrandom
returnreadtline(
filename,
random.randint(0,getfilelines(filename)),
)


if__name__=="__main__":
importsys
importos
iflen(sys.argv)==1:
printgetrandomline("/home/tim/documents/users.csv")
else:
forfinfilter(os.path.isfile,sys.argv[1:]):
printgetrandomline(f)

對於超大文件建議用逐行或分塊的方式處理;逐行處理可能慢一些,但編碼更簡單清晰一點;上面給出的是按分塊方式處理的。

Ⅶ Python如何讀取csv文件某一列的每一行數據,並判斷該數值是否滿足條件

讀取csv文件,用的是csv.reader()這個方法。返回結果是一個_csv.reader的對象,我們可以對這個對象進行遍歷,輸出每一行,某一行,或某一列。代碼如下:

Ⅷ 2018-01-06 python讀取csv某一行

我要讀取csv文件中的某一行,寫到這里的時候就不知道咋整了:

至此,我想啊,怎麼輸出一行來呢?明明很簡單的問題,看來是python基礎不過關吶! 不過沒關系,所有的牛逼不都是這么一點一滴積累起來的么?!

保持好奇心和求知慾就好啦!!!

我把文件全部輸出( print row )是這樣子的:

假設我完全不知道上面的 csv_reader 就是一個迭代器,那麼我可能會認為這就是一個二維數組,那麼我直接 csv_reader[0] 輸出一行試試嘛!反正又不要錢!

失敗!*1

既然這樣子不行,那麼我把它整成二維數組不就好啦!

噢啦~打完收工!

但是這種寫法...... 一點都不優雅啊!你直接寫個0是什麼意思啊?裸奔嗎?你append是啥意思啊?不嫌累的慌嗎?這么寫跟C有什麼區別啊!作為貴族你的尊嚴呢?!

上面是我們根據行號來查找數據,但是假如我們要 根據行內數據特徵來查找 呢?

ang~介是嘛?! DictReader !!!

輸出的是字典了喲~ 第一行就是字典的key ,下面對應的就是value:

假如我要找TestResult=「1」的行,咋整?

輸出:

閱讀全文

與python讀文件某一行相關的資料

熱點內容
演算法公司創始人 瀏覽:655
學編程能上手嗎 瀏覽:793
聽歌為什麼都要下載app 瀏覽:343
java網路文件下載 瀏覽:674
linux裝入u盤 瀏覽:479
程序員大學生學歷 瀏覽:25
文件解壓的時候玩游戲 瀏覽:794
在單鏈表中刪除值相同的多餘結點的演算法 瀏覽:745
如何查看windows伺服器運行時間 瀏覽:475
比澤爾半封閉式壓縮機 瀏覽:373
新網雲伺服器系統更換 瀏覽:717
攤鏈app是干什麼的 瀏覽:345
手機能在哪裡解壓 瀏覽:142
什麼公司可以出售伺服器 瀏覽:790
php多用戶博客系統 瀏覽:591
短線買入信號源碼 瀏覽:655
PDF三等分 瀏覽:454
視頻的文件夾怎麼找回 瀏覽:2
h3ccisco命令對比 瀏覽:805
python定義一個模塊 瀏覽:937