Python实现读取文件中的特定行的方法详解!

  • A+
所属分类:Python学习

Python实现读取文件中的特定行的方法详解!

这篇文章主要为大家详细介绍了如何在Python中实现读取文件中的特定行,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下

在Python中,读取文件中的特定行通常涉及到几个步骤:打开文件,遍历行,然后定位到你感兴趣的行。下面是一个简单的例子,说明如何读取文件中的特定行(例如第n行):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def read_specific_line(file_path, line_number):
with open(file_path, 'r') as file:
# 逐行读取文件,直到找到所需的行号
for i, line in enumerate(file, 1):
if i == line_number:
return line.strip()  # strip() 用于移除行尾的换行符
return None  # 如果没有找到指定行号,则返回None
# 替换为你的文件路径和要读取的行号
file_path = "path_to_your_file.txt"
line_number = 5  # 读取第5行
# 调用函数并打印结果
specific_line = read_specific_line(file_path, line_number)
if specific_line:
print(f"Line {line_number}: {specific_line}")
else:
print(f"Line {line_number} not found in the file.")

在这个例子中,enumerate()函数用于在遍历文件的同时计数行号。enumerate()的第二个参数1是起始计数值,因为我们通常认为文件的第一行是行号1。strip()方法用于移除行尾的换行符(\n),这样你就可以得到一个干净的字符串。

如果你知道文件不是特别大,并且想直接访问特定行而不需要遍历整个文件,你也可以先将所有行读入一个列表,然后直接通过索引访问:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
def read_specific_line_direct(file_path, line_number):
with open(file_path, 'r') as file:
lines = file.readlines()  # 读取所有行到列表中
if 0 < line_number <= len(lines):
return lines[line_number - 1].strip()  # 注意列表索引是从0开始的,所以要减1
return None
# 使用与之前相同的文件路径和行号
file_path = "path_to_your_file.txt"
line_number = 5
# 调用函数并打印结果
specific_line = read_specific_line_direct(file_path, line_number)
if specific_line:
print(f"Line {line_number}: {specific_line}")
else:
print(f"Line {line_number} not found in the file.")

请注意,这种方法将整个文件内容加载到内存中,因此对于非常大的文件可能会导致性能问题或内存不足。在大多数情况下,第一种方法(逐行读取)是更可取的选择,因为它更加灵活且内存效率更高。

方法补充

除了上文的方法,小编还为大家整理了一下其他Python读取文件指定行的方法,希望对大家有所帮助

python读取文件指定行的三种方法

1.行遍历实现

在python中如果要将一个文件完全加载到内存中,通过file.readlines()即可,但是在文件占用较高时,我们是无法完整的将文件加载到内存中的,这时候就需要用到python的file.readline()进行迭代式的逐行读取:

1
2
3
4
5
6
7
8
9
10
11
filename = 'hello.txt'
with open(filename, 'r') as file:
line = file.readline()
counts = 1
while line:
if counts >= 50000000:
break
line = file.readline()
​​​​​​​        counts += 1

这里我们的实现方式是先用一个with语句打开一个文件,然后用readline()函数配合while循环逐行加载,最终通过一个序号标记来结束循环遍历,输出文件第50000000行的内容。该代码的执行效果如下:

dechin@ubuntu2004:~/projects/gitlab/dechin/$ time python3 get_line.py

real    0m10.359s
user    0m10.062s

sys     0m0.296s

可以看到这里的耗时为10s多一些。

2.linecache实现

虽然在python的readline函数中并没有实现读取指定行内容的方案,但是在另一个库linecache中是实现了的,由于使用的方式较为简单,这里直接放上代码示例供参考:

1
2
3
4
5
filename = 'hello.txt'
import linecache
text = linecache.getline(filename, 50000000)

该代码的执行结果如下:

dechin@ubuntu2004:~/projects/gitlab/dechin/$ time python3 get_line.py

real    0m11.904s
user    0m5.672s

sys     0m6.231s

虽然在实现方式上简化了许多,但是我们发现这个实现的用时超过了11s,还不如我们自己手动实现的循环遍历方案。因此如果是对于性能有一定要求的场景,是不建议采用这个方案的。

3.命令行sed获取

我们知道用Linux系统本身自带的sed指令也是可以获取到文件指定行或者是指定行范围的数据的,其执行指令为:sed -n 50000000p filename即表示读取文件的第50000000行的内容。同时结合python的话,我们可以在python代码中执行系统指令并获取输出结果:

1
2
3
4
5
filename = 'hello.txt'
import os
result = os.popen('sed -n {}p {}'.format(50000000, filename)).read()

需要注意的是,如果直接运行os.system()是没有返回值的,只有os.popen()是有返回值的,并且需要在尾巴加上一个read()的选项。该代码的执行结果如下:

dechin@ubuntu2004:~/projects/gitlab/dechin/$ time python3 get_line.py

real    0m2.532s
user    0m0.032s

sys     0m0.020s

可以看到直接使用sed指令的执行速度很快,但是用这种方法并不是一本万利的,比如以下这个例子:

1
2
3
4
5
filename = 'hello.txt'
import os
result = os.popen('sed -n {}p {}'.format(500, filename)).read()

我们把读取第50000000行内容改为读取第500行的内容,再运行一次程序:

dechin@ubuntu2004:~/projects/gitlab/dechin/$ time python3 get_line.py

real    0m2.540s

user    0m0.037ssys     0m0.013s

然而我们发现这个速度并没有因为要读取的行数减少了而变少,而是几乎保持不变的。

 

学习资料见知识星球。

以上就是今天要分享的技巧,你学会了吗?若有什么问题,欢迎在下方留言。

快来试试吧,小琥 my21ke007。获取 1000个免费 Excel模板福利​​​​!

更多技巧, www.excelbook.cn

欢迎 加入 零售创新 知识星球,知识星球主要以数据分析、报告分享、数据工具讨论为主;

Python实现读取文件中的特定行的方法详解!

你将获得:

1、价值上万元的专业的PPT报告模板。

2、专业案例分析和解读笔记。

3、实用的Excel、Word、PPT技巧。

4、VIP讨论群,共享资源。

5、优惠的会员商品。

6、一次付费只需99元,即可下载本站文章涉及的文件和软件。

  • 我的微信
  • weinxin
  • 我的知识星球
  • weinxin

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: