我正在使用 for
循环读取文件,但我只想读取特定的行,比如第 #26
行和 #30
行。有没有内置的功能可以实现这个要求呢?
@楼主,你可以使用enumerate函数
for n,line in enumerate(open("file")):
if n+1 in [26,30]: # or n in [25,29]
print line.rstrip()
file = '/path/to/file_to_be_read.txt'
with open(file) as f:
print f.readlines()[26]
print f.readlines()[30]
readlines()
后,迭代器将被耗尽,第二次调用将返回一个空列表或抛出错误(记不清了)。 - Paul H打印所需的行。 打印所需行上方/下方的行。
def dline(file,no,add_sub=0):
tf=open(file)
for sno,line in enumerate(tf):
if sno==no-1+add_sub:
print(line)
tf.close()
执行---->dline("D:\dummy.txt",6) 即 dline("文件路径", 行号, 如果你想要搜索行的上一行则输入1,如果要下一行则输入-1,这是可选项,默认值为0)
您可以使用最简单的逻辑之一,将字符串拆分为数组或列表来完成它。
f = open('filepath')
r = f.read()
s = r.split("\n")
n = [linenumber1, linenumber2] # [26, 29] in your
#case
for x in n:
print(s[x-1])
f.close()
file = open("files.txt","r")
lines = file.readlines() ## 转换为行列表
datas = lines[11:] ## 读取特定行
不要使用readlines
!
我的解决方案是:
with open(filename) as f:
specify = [26, 30]
results = list(
map(lambda line: line[1],
filter(lambda line: line[0] in specify,
enumerate(f))
)
)
测试如下,针对一个 6.5G
的文件:
import time
filename = 'a.txt'
start = time.time()
with open(filename, 'w') as f:
for i in range(10_000_000):
f.write(f'{str(i)*100}\n')
end1 = time.time()
with open(filename) as f:
specify = [26, 30]
results = list(
map(lambda line: line[1],
filter(lambda line: line[0] in specify,
enumerate(f))
)
)
end2 = time.time()
print(f'write time: {end1-start}')
print(f'read time: {end2-end1}')
# write time: 14.38945460319519
# read time: 8.380386352539062
我认为这会起作用
open_file1 = open("E:\\test.txt",'r')
read_it1 = open_file1.read()
myline1 = []
for line1 in read_it1.splitlines():
myline1.append(line1)
print myline1[0]
f = open(filename, 'r')
totalLines = len(f.readlines())
f.close()
f = open(filename, 'r')
lineno = 1
while lineno < totalLines:
line = f.readline()
if lineno == 26:
doLine26Commmand(line)
elif lineno == 30:
doLine30Commmand(line)
lineno += 1
f.close()
从特定行读取:
n = 4 # for reading from 5th line
with open("write.txt",'r') as t:
for i,line in enumerate(t):
if i >= n: # i == n-1 for nth line
print(line)