Ⅰ 如何用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”的行,咋整?
输出: