iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Python读取文件比open快十倍的库fileinput
  • 352
分享到

Python读取文件比open快十倍的库fileinput

2024-04-02 19:04:59 352人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

目录1. 从标准输入中读取2. 单独打开一个文件3. 批量打开多个文件4. 读取的同时备份文件5. 标准输出重定向替换6. 不得不介绍的方法7. 进阶一点的玩法8. 列举一些实用案例

使用 open 函数去读取文件,似乎是所有 python 工程师的共识。

今天明哥要给大家推荐一个比 open 更好用、更优雅的读取文件方法 – 使用 fileinput

1. 从标准输入中读取

当你的 Python 脚本没有传入任何参数时,fileinput 默认会以 stdin 作为输入源


# demo.py
import fileinput

for line in fileinput.input():
    print(line) 

效果如下,不管你输入什么,程序会自动读取并再打印一次,像个复读机似的。


$ python demo.py 
hello
hello

python
python

2. 单独打开一个文件

脚本的内容如下


import fileinput

with fileinput.input(files=('a.txt',)) as file:
    for line in file:
        print(f'{fileinput.filename()} 第{fileinput.lineno()}行: {line}', end='') 

其中 a.txt 的内容如下

hello
world

执行后就会输出如下


$ python demo.py
a.txt 第1行: hello
a.txt 第2行: world

需要说明的一点是,fileinput.input() 默认使用 mode='r' 的模式读取文件,如果你的文件是二进制的,可以使用mode='rb' 模式。fileinput 有且仅有这两种读取模式。

3. 批量打开多个文件

从上面的例子也可以看到,我在 fileinput.input 函数中传入了 files 参数,它接收一个包含多个文件名的列表或元组,传入一个就是读取一个文件,传入多件就是读取多个文件。


import fileinput

with fileinput.input(files=('a.txt', 'b.txt')) as file:
    for line in file:
        print(f'{fileinput.filename()} 第{fileinput.lineno()}行: {line}', end='') 

a.txtb.txt 的内容分别是


$ cat a.txt
hello
world
$ cat b.txt
hello
python

运行后输出结果如下,由于 a.txtb.txt 的内容被整合成一个文件对象 file ,因此 fileinput.lineno() 只有在读取一个文件时,才是原文件中真实的行号。


$ python demo.py
a.txt 第1行: hello
a.txt 第2行: world
b.txt 第3行: hello
b.txt 第4行: python

如果想要在读取多个文件的时候,也能读取原文件的真实行号,可以使用 fileinput.filelineno() 方法


import fileinput

with fileinput.input(files=('a.txt', 'b.txt')) as file:
    for line in file:
        print(f'{fileinput.filename()} 第{fileinput.filelineno()}行: {line}', end='') 

运行后,输出如下


$ python demo.py
a.txt 第1行: hello
a.txt 第2行: world
b.txt 第1行: hello
b.txt 第2行: python

这个用法和 glob 模块简直是绝配


import fileinput
import glob
 
for line in fileinput.input(glob.glob("*.txt")):
    if fileinput.isfirstline():
        print('-'*20, f'Reading {fileinput.filename()}...', '-'*20)
    print(str(fileinput.lineno()) + ': ' + line.upper(), end="")

运行效果如下


$ python demo.py
-------------------- Reading b.txt... --------------------
1: HELLO
2: PYTHON
-------------------- Reading a.txt... --------------------
3: HELLO
4: WORLD

4. 读取的同时备份文件

fileinput.input 有一个 backup 参数,你可以指定备份的后缀名,比如 .bak


import fileinput
with fileinput.input(files=("a.txt",), backup=".bak") as file:
    for line in file:
        print(f'{fileinput.filename()} 第{fileinput.lineno()}行: {line}', end='') 

运行的结果如下,会多出一个 a.txt.bak 文件


$ ls -l a.txt*
-rw-r--r--  1 MING  staff  12  2 27 10:43 a.txt

$ python demo.py
a.txt 第1行: hello
a.txt 第2行: world

$ ls -l a.txt*
-rw-r--r--  1 MING  staff  12  2 27 10:43 a.txt
-rw-r--r--  1 MING  staff  42  2 27 10:39 a.txt.bak

5. 标准输出重定向替换

fileinput.input 有一个 inplace 参数,表示是否将标准输出的结果写回文件,默认不取代

请看如下一段测试代码


import fileinput

with fileinput.input(files=("a.txt",), inplace=True) as file:
    print("[INFO] task is started...") 
    for line in file:
        print(f'{fileinput.filename()} 第{fileinput.lineno()}行: {line}', end='') 
    print("[INFO] task is closed...") 

运行后,会发现在 for 循环体内的 print 内容会写回到原文件中了。而在 for 循环体外的 print 则没有变化。


$ cat a.txt
hello
world

$ python demo.py
[INFO] task is started...
[INFO] task is closed...

$ cat a.txt 
a.txt 第1行: hello
a.txt 第2行: world

利用这个机制,可以很容易的实现文本替换。


import sys
import fileinput

for line in fileinput.input(files=('a.txt', ), inplace=True):
    #将windows/DOS格式下的文本文件转为linux的文件
    if line[-2:] == "\r\n":  
        line = line + "\n"
    sys.stdout.write(line)

附:如何实现 DOS 和 UNIX 格式互换以供程序测试,使用 vim 输入如下指令即可

DOS转UNIX::setfilefORMat=unix
UNIX转DOS::setfileformat=dos

6. 不得不介绍的方法

如果只是想要 fileinput 当做是替代 open 读取文件的工具,那么以上的内容足以满足你的要求。

fileinput.filenam()
返回当前被读取的文件名。 在第一行被读取之前,返回 None

fileinput.fileno()
返回以整数表示的当前文件“文件描述符”。 当未打开文件时(处在第一行和文件之间),返回 -1

fileinput.lineno()
返回已被读取的累计行号。 在第一行被读取之前,返回 0。 在最后一个文件的最后一行被读取之后,返回该行的行号。

fileinput.filelineno()
返回当前文件中的行号。 在第一行被读取之前,返回 0。 在最后一个文件的最后一行被读取之后,返回此文件中该行的行号。

但若要想基于 fileinput 来做一些更加复杂的逻辑,也许你会需要用到如下这几个方法

fileinput.isfirstline()
如果刚读取的行是其所在文件的第一行则返回 True,否则返回 False

fileinput.isstdin()
如果最后读取的行来自 sys.stdin 则返回 True,否则返回 False

fileinput.nextfile()
关闭当前文件以使下次迭代将从下一个文件(如果存在)读取第一行;不是从该文件读取的行将不会被计入累计行数。 直到下一个文件的第一行被读取之后文件名才会改变。 在第一行被读取之前,此函数将不会生效;它不能被用来跳过第一个文件。 在最后一个文件的最后一行被读取之后,此函数将不再生效。

fileinput.close()关闭序列。

7. 进阶一点的玩法

fileinput.input() 中有一个 openhook 的参数,它支持用户传入自定义的对象读取方法。

若你没有传入任何的勾子,fileinput 默认使用的是 open 函数。

fileinput 为我们内置了两种勾子供你使用

1. fileinput.hook_compressed(*filename*, *mode*)

使用 gzipbz2 模块透明地打开 gzip 和 bzip2 压缩的文件(通过扩展名 '.gz''.bz2' 来识别)。 如果文件扩展名不是 '.gz''.bz2',文件会以正常方式打开(即使用 open() 并且不带任何解压操作)。使用示例:

 fi = fileinput.FileInput(openhook=fileinput.hook_compressed)

2.  fileinput.hook_encoded(*encoding*, *errors=None*)

返回一个通过 open() 打开每个文件的钩子,使用给定的 encoding 和 errors 来读取文件。使用示例:

 fi = fileinput.FileInput(openhook=fileinput.hook_encoded("utf-8", "surrogateescape"))

如果你自己的场景比较特殊,以上的三种勾子都不能满足你的要求,你也可以自定义。

这边我举个例子来抛砖引玉下

假如我想要使用 fileinput 来读取网络上的文件,可以这样定义勾子。

先使用 requests 下载文件到本地

再使用 open 去读取它


def online_open(url, mode):
    import requests
    r = requests.get(url) 
    filename = url.split("/")[-1]
    with open(filename,'w') as f1:
        f1.write(r.content.decode("utf-8"))
    f2 = open(filename,'r')
    return f2

直接将这个函数传给 openhoos 即可


import fileinput

file_url = 'https://www.csdn.net/robots.txt'
with fileinput.input(files=(file_url,), openhook=online_open) as file:
    for line in file:
        print(line, end="")

运行后按预期一样将 CSDN 的 robots 的文件打印了出来


User-agent: * 
Disallow: /scripts 
Disallow: /public 
Disallow: /CSS/ 
Disallow: /images/ 
Disallow: /content/ 
Disallow: /ui/ 
Disallow: /js/ 
Disallow: /scripts/ 
Disallow: /article_preview.html* 
Disallow: /tag/
Disallow: /*?*
Disallow: /link/

Sitemap: Https://www.csdn.net/sitemap-aggpage-index.xml
Sitemap: https://www.csdn.net/article/sitemap.txt 

8. 列举一些实用案例

案例一:读取一个文件所有行


import fileinput
for line in fileinput.input('data.txt'):
  print(line, end="")

案例二:读取多个文件所有行


import fileinput
import glob
 
for line in fileinput.input(glob.glob("*.txt")):
    if fileinput.isfirstline():
        print('-'*20, f'Reading {fileinput.filename()}...', '-'*20)
    print(str(fileinput.lineno()) + ': ' + line.upper(), end="")

案例三:利用fileinput将CRLF文件转为LF


import sys
import fileinput

for line in fileinput.input(files=('a.txt', ), inplace=True):
    #将Windows/DOS格式下的文本文件转为Linux的文件
    if line[-2:] == "\r\n":  
        line = line + "\n"
    sys.stdout.write(line)

案例四:配合 re 做日志分析:取所有含日期的行


#--样本文件--:error.log
aaa
1970-01-01 13:45:30  Error: **** Due to System Disk spacke not enough...
bbb
1970-01-02 10:20:30  Error: **** Due to System Out of Memory...
ccc
 
#---测试脚本---
import re
import fileinput
import sys
 
pattern = '\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}'
 
for line in fileinput.input('error.log',backup='.bak',inplace=1):
    if re.search(pattern,line):
        sys.stdout.write("=> ")
        sys.stdout.write(line)
 
#---测试结果---
=> 1970-01-01 13:45:30  Error: **** Due to System Disk spacke not enough...
=> 1970-01-02 10:20:30  Error: **** Due to System Out of Memory...

案例五:利用fileinput实现类似于grep的功能


import sys
import re
import fileinput
 
pattern= re.compile(sys.argv[1])
for line in fileinput.input(sys.argv[2]):
    if pattern.match(line):
        print(fileinput.filename(), fileinput.filelineno(), line)
$ ./test.py import.*re *.py
#查找所有py文件中,含import re字样的
addressBook.py  2   import re
addressBook1.py 10  import re
addressBook2.py 18  import re
test.py         238 import re

9. 写在最后

fileinput 是对 open 函数的再次封装,在仅需读取数据的场景中, fileinput 显然比 open 做得更专业、更人性,当然在其他有写操作的复杂场景中,fileinput 就无能为力啦,本身从 fileinput 的命名上就知道这个模块只专注于输入(读)而不是输出(写)。

以上就是Python读取文件比open快十倍的库fileinput的详细内容,更多关于Python读取文件库fileinput的资料请关注编程网其它相关文章!

--结束END--

本文标题: Python读取文件比open快十倍的库fileinput

本文链接: https://www.lsjlt.com/news/155409.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Python读取文件比open快十倍的库fileinput
    目录1. 从标准输入中读取2. 单独打开一个文件3. 批量打开多个文件4. 读取的同时备份文件5. 标准输出重定向替换6. 不得不介绍的方法7. 进阶一点的玩法8. 列举一些实用案例...
    99+
    2024-04-02
  • python 使用fileinput读取文件
    目录1. 从标准输入中读取 2. 单独打开一个文件 3. 批量打开多个文件 4. 读取的同时备份文件 5. 标准输出重定向替换 6. 不得不介绍的方法 7. 进阶一点的玩法 8. 列...
    99+
    2024-04-02
  • python如何使用fileinput读取文件
    这篇文章主要介绍python如何使用fileinput读取文件,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!fileinput 是 Python 的内置模块,但我相信,不少人对它都是陌生的。今天我把 fileinpu...
    99+
    2023-06-14
  • Python open()读取文件 Un
    Python 读取文件 f = open('D:/python/cpwords.txt','r',encoding='utf-8') print(*f) 读取Unicode格式的文本时,需要使用 utf-16 编码格式: f...
    99+
    2023-01-31
    文件 Python open
  • 怎么使用python open读取文件
    要使用Python的open函数来读取文件,你需要使用以下步骤:1. 打开文件:使用open函数打开文件,并传入文件路径和打开模式作...
    99+
    2023-09-14
    python
  • python open读取文件内容时的mode模式解析
    Python可以使用open函数来实现文件的打开,关闭,读写操作; Python3中的open函数定义为:open(file, mode='r', buffering...
    99+
    2024-04-02
  • python读写文件with open的介绍
    目录一、案例一(读取)1、读取文件 基本实现2、读取文件 中级实现3、读取文件 终极实现二、案例二(写入)1、、写入文件 基本实现2、写入文件终极实现简介: 使用python的过程中...
    99+
    2024-04-02
  • Golang文件读取操作:快速读取大文件的技巧
    Golang文件读取操作:快速读取大文件的技巧,需要具体代码示例 在Golang程序设计中,文件读取是一个非常常见的操作。但当需要读取大文件时,通常是一件比较耗费时间和资源的操作。因此,如何快速读取大文件是一...
    99+
    2024-01-19
    大文件 Golang 文件读取
  • python读取access文件并入库
    Python读取access文件时和读取Excel文件不是很一样,当然用的工具也不一样,在读取excel中的数据时用的是xlrd,而读取access文件时用的则是pypyodbc。 简要安装过程:1、首先要安装access驱动(Acces...
    99+
    2023-01-31
    文件 python access
  • python文件的读取
    python文件的读取 1.文件的读取1.read() 读取整个文件2.readline() 每次读取一行文件3. readlines() 读取文件的所有行 2.文件的写入1.以"x"方式...
    99+
    2023-09-01
    python 数据分析 pandas numpy 文件读取
  • 利用Python中的内置open函数读取二进制文件
    在python中读取一个文本文件相信大家都比较熟悉了,但如果我们遇到一个二进制文件要读取怎么办呢?我们尝试使用 Python 中的内置 open 函数使用默认读取模式读取 zip 文...
    99+
    2024-04-02
  • python open读取文件内容时的mode模式实例分析
    今天小编给大家分享一下python open读取文件内容时的mode模式实例分析的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来...
    99+
    2023-06-30
  • 如何利用Python快速读取CSV文件
    使用 pandas 库可快速读取 csv 文件:首先安装 pandas。使用 read_csv() 函数读取 csv 文件并将其存储在数据框中。使用 head() 函数查看数据框的前几行...
    99+
    2024-04-04
    python csv 数据处理 csv文件
  • Python数组文件读取速度有多快?
    Python作为一种高级编程语言,有着非常强大的数据处理和分析能力。对于数据处理来说,Python的数组文件读取速度是非常关键的。那么,Python数组文件读取速度有多快呢?本文将从以下几个方面进行介绍和演示: Python数组文件读取方...
    99+
    2023-07-06
    实时 数组 文件
  • 【Python】json文件的读取
    文章目录 1. json简介2.json的使用规范3.json文件的书写4.json文件的读取 1. json简介 JSON(JavaScript Object Notation)是一...
    99+
    2023-10-23
    python json 开发语言
  • Python的open函数文件读写线程不
    工作中遇到的问题:如何在多线程的程序中同时记录日志? 最初图省事,使用了最原始的open函数来写日志,因为开始使用的写文件模式的是追加('a'),发现并没有线程不安全的现象,各个线程的的日志信息都写入到了日志文件中。 后来将写文件模式改成...
    99+
    2023-01-31
    线程 函数 文件
  • 快速上手pandas:使用该库读取Excel文件的快捷方法
    pandas是Python中一款重要的数据分析库,能够简化数据的读取、清洗和处理过程,目前已成为数据分析工作的标配。在数据分析过程中,Excel往往是数据来源之一,因此本文将介绍使用pandas读取Excel文件的快捷方法。 使...
    99+
    2024-01-19
    Pandas Excel文件 快捷方法
  • 使用python的netCDF4库读取.nc文件 和 创建.nc文件
      使用python netCDF4库读取.nc文件 和 创建.nc文件  1. 介绍  .nc(network Common Data Format)文件是气象上常用的数据格式,python上读取.nc使用较多的库为netCDF4这个库,...
    99+
    2023-06-02
  • python中读取文件的read、rea
       #读取文件所有内容,返回字符串对象,python默认以文本方式读取文件,遇到结束符读取结束。 fr = open('lenses.txt')read = fr.read()print(type(read),read)#读取文件中的一...
    99+
    2023-01-30
    文件 python rea
  • python怎么读取文件夹中的文件
    读取文件夹中的文件可以使用Python的os模块和glob模块。以下是两种常用的方法: 方法一:使用os模块的listdir函数 i...
    99+
    2024-02-29
    python
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作