Python之fileinput

2024-04-10 03:38
文章标签 python fileinput

本文主要是介绍Python之fileinput,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

fileinput module
fileinput module可以对一个或多个文件中的内容进行迭代、遍历等操作。该模块的input()函数有点类似文件readlines()方法。
区别在于前者是一个迭代对象(iterable object),需要用for循环迭代,后者是一次性读取所有行。

用fileinput对文件进行循环遍历,格式化输出,查找、替换等操作,非常方便。

1. 典型用法

import fileinput
for line in fileinput.input('D:\\HeadFirstPython\\chapter1\\data.txt'):print(line, end = "")
似乎比 with open(filename) as f: for i in f: print(i) 这种要好一些

2. FUNCTIONS

close()
    Close the sequence.
filelineno()
    Return the line number in the current file. Before the first line
    has been read, returns 0. After the last line of the last file has
    been read, returns the line number of that line within the file.
返回当前读取的文件内容的行数
filename()
    Return the name of the file currently being read.
    Before the first line has been read, returns None.
input(files=None, inplace=False, backup='', bufsize=0, mode='r', openhook=None)
    Return an instance of the FileInput class, which can be iterated.    
    The parameters are passed to the constructor of the FileInput class.
    The returned instance, in addition to being an iterator,
    keeps global state for the functions of this module,.
files:                  #文件的路径列表,默认是stdin方式,多文件['1.txt','2.txt',...]
inplace:                #是否将标准输出的结果写回文件,默认不取代,即不写入文件
backup:                 #备份文件的扩展名,只指定扩展名,如.bak。如果该文件的备份文件已存在,则会自动覆盖。
bufsize:                #缓冲区大小,默认为0,如果文件很大,可以修改此参数,一般默认即可
mode:                   #读写模式,默认为只读
openhook:               #该钩子用于控制打开的所有文件,比如说编码方式等;
isfirstline()
    Returns true the line just read is the first line of its file,
    otherwise returns false.
注:主要是当一次性读取多个文件时,区分不同的文件

isstdin()
    Returns true if the last line was read from sys.stdin,
    otherwise returns false.
判断最后一行是否从stdin中读取,stdin指标准输入, 默认是从键盘输入
lineno()
    Return the cumulative line number of the line that has just been read.
    Before the first line has been read, returns 0. After the last line
    of the last file has been read, returns the line number of that line.
返回当前已经读取的行的数量(或者序号), 是累计的行数
nextfile()
    Close the current file so that the next iteration will read the first
    line from the next file (if any); lines not read from the file will
    not count towards the cumulative line count. The filename is not
    changed until after the first line of the next file has been read.
    Before the first line has been read, this function has no effect;
    it cannot be used to skip the first file. After the last line of the
    last file has been read, this function has no effect.

3. 常见例子
3.1 利用fileinput读取一个文件所有行

import fileinput
with fileinput.input('D:\\HeadFirstPython\\chapter1\\data.txt') as f:for line in f:print(fileinput.filename(),'|','Line Number:',fileinput.filelineno(),'|: ',line, end = "")
output:

D:\HeadFirstPython\chapter1\data.txt | Line Number: 1 |:  Perl
D:\HeadFirstPython\chapter1\data.txt | Line Number: 2 |:  Java
D:\HeadFirstPython\chapter1\data.txt | Line Number: 3 |:  C/C++
D:\HeadFirstPython\chapter1\data.txt | Line Number: 4 |:  Shell
命令行方式:
#test.py
import fileinput
for line in fileinput.input():print(fileinput.filename(),'|','Line Number:',fileinput.lineno(),'|: ',line, end = "")
output:

D:\HeadFirstPython\chapter1>python.exe test.py data.txt
data.txt | Line Number: 1 |: Python
data.txt | Line Number: 2 |: Java
data.txt | Line Number: 3 |: C/C++
data.txt | Line Number: 4 |: Shell
3.2 利用fileinput对多文件操作,并原地修改内容
3.2.1 文件内容:

#test02.py
import fileinput
def process(line):return(line.rstrip() + " line")file_names = ['D:\\HeadFirstPython\\chapter1\\1.txt', 'D:\\HeadFirstPython\\chapter1\\2.txt']
for line in fileinput.input(file_names, inplace = 1):print(process(line))
直接F5, 或者进入命令行
D:\HeadFirstPython\chapter1>python.exe test02.py
得到结果是1.txt/2.txt中变成如下:
1.txt
first line
second line2.txt
third line 
fourth line 
注:如果inpalce = False,则不会向1.txt/2.txt中插入,而会直接打印到屏幕
3.2.2 命令行方式:
#test03.py
import fileinput
def process(line):return(line.rstrip() + ' line') 
for line in fileinput.input(inplace = True):print(process(line))
#执行命令:
D:\HeadFirstPython\chapter1>python.exe test03.py 1.txt 2.txt
3.3 利用fileinput实现文件内容替换,并将原文件作备份
#test04.py
import fileinput
for line in fileinput.input("D:\\HeadFirstPython\\chapter1\\data.txt", backup = ".bak", inplace = 1):print(line.rstrip().replace("Python", "Perl"))

output:

Perl
Java
C/C++
Shell
3.4 利用fileinput对文件简单处理
#FileName: test.py
import sys
import fileinputfor line in fileinput.input('150827.txt'):sys.stdout.write('=> ')sys.stdout.write(line)
#注:print是对sys.stout.write的友好封装, 并且print可以指定sep,但是sys.stout.write也有它自己的优势
3.5 利用fileinput批处理文件
import glob
import fileinput
a = glob.iglob('15*.txt')
for line in fileinput.input(a):if fileinput.isfirstline():print('-'*20, 'Reading %s...' % fileinput.filename(), '-'*20)print(str(fileinput.lineno()) + ': ' + line.upper())
#备注:glob中就两个知识点:glob和iglob,其中iglob把结果变成生成器iterator
3.6 利用fileinput及re做日志分析: 提取所有含日期的行
import re
import fileinput
import syspattern = '\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}'
#pattern = '1970-01-01 13:45:30'
for line in fileinput.input('error.log', backup = '.bak', inplace = False):if re.findall(pattern,line):sys.stdout.write('=>')sys.stdout.write(line)
测试结果:

=>1970-01-01 13:45:30  Error: **** Due to System1 Disk spacke not enough...
=>1970-01-02 13:45:30  Error: **** Due to System2 Disk spacke not enough...
=>1970-01-03 10:20:30  Error: **** Due to System3 Out of Memory...
=>1970-01-04 10:20:30  Error: **** Due to System4 Out of Memory...
3.7 利用fileinput及re做分析: 提取符合条件的电话号码
#---样本文件: phone.txt---
010-110-12345
800-333-1234
010-99999999
05718888888
021-88888888
#---测试脚本: test.py---
import re
import fileinputpattern = '[010|021]-\d{8}'  #提取区号为010或021电话号码,格式:010-12345678
#pattern = '010-110-12345'
for line in fileinput.input('phone.txt'):if re.findall(pattern,line):print('=' * 50)print('Filename:'+ fileinput.filename()+ ' | Line Number:'+str(fileinput.lineno())+ ' | '+ line, end = '')
output:

==================================================
Filename:phone.txt | Line Number:3 | 010-99999999
==================================================
Filename:phone.txt | Line Number:5 | 021-88888888
#注:print中, '+' 和 ',' 都可以, 但是','打印出来一个空格, 而'+'则没有
3.8 csv和fileinput比较:
import csv,fileinputwith open("app_dim_pop_phy_vender.csv") as csvfile:reader = csv.reader(csvfile)#print(reader)for row in reader:vender_id,vender_name,cx_dept_id,company_id,company_name = row#print(vender_id + '\t' + vender_name + '\t' + cx_dept_id + '\t' + company_id + '\t' + company_name)for row in fileinput.input("app_dim_pop_phy_vender.csv"):vender_id,vender_name,cx_dept_id,company_id,company_name = row.split(',')print(vender_id + '\t' + vender_name + '\t' + cx_dept_id + '\t' + company_id + '\t' + company_name)














这篇关于Python之fileinput的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/889983

相关文章

使用Python删除Excel中的行列和单元格示例详解

《使用Python删除Excel中的行列和单元格示例详解》在处理Excel数据时,删除不需要的行、列或单元格是一项常见且必要的操作,本文将使用Python脚本实现对Excel表格的高效自动化处理,感兴... 目录开发环境准备使用 python 删除 Excphpel 表格中的行删除特定行删除空白行删除含指定

Python通用唯一标识符模块uuid使用案例详解

《Python通用唯一标识符模块uuid使用案例详解》Pythonuuid模块用于生成128位全局唯一标识符,支持UUID1-5版本,适用于分布式系统、数据库主键等场景,需注意隐私、碰撞概率及存储优... 目录简介核心功能1. UUID版本2. UUID属性3. 命名空间使用场景1. 生成唯一标识符2. 数

Python办公自动化实战之打造智能邮件发送工具

《Python办公自动化实战之打造智能邮件发送工具》在数字化办公场景中,邮件自动化是提升工作效率的关键技能,本文将演示如何使用Python的smtplib和email库构建一个支持图文混排,多附件,多... 目录前言一、基础配置:搭建邮件发送框架1.1 邮箱服务准备1.2 核心库导入1.3 基础发送函数二、

Python包管理工具pip的升级指南

《Python包管理工具pip的升级指南》本文全面探讨Python包管理工具pip的升级策略,从基础升级方法到高级技巧,涵盖不同操作系统环境下的最佳实践,我们将深入分析pip的工作原理,介绍多种升级方... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核

基于Python实现一个图片拆分工具

《基于Python实现一个图片拆分工具》这篇文章主要为大家详细介绍了如何基于Python实现一个图片拆分工具,可以根据需要的行数和列数进行拆分,感兴趣的小伙伴可以跟随小编一起学习一下... 简单介绍先自己选择输入的图片,默认是输出到项目文件夹中,可以自己选择其他的文件夹,选择需要拆分的行数和列数,可以通过

Python中反转字符串的常见方法小结

《Python中反转字符串的常见方法小结》在Python中,字符串对象没有内置的反转方法,然而,在实际开发中,我们经常会遇到需要反转字符串的场景,比如处理回文字符串、文本加密等,因此,掌握如何在Pyt... 目录python中反转字符串的方法技术背景实现步骤1. 使用切片2. 使用 reversed() 函

Python中将嵌套列表扁平化的多种实现方法

《Python中将嵌套列表扁平化的多种实现方法》在Python编程中,我们常常会遇到需要将嵌套列表(即列表中包含列表)转换为一个一维的扁平列表的需求,本文将给大家介绍了多种实现这一目标的方法,需要的朋... 目录python中将嵌套列表扁平化的方法技术背景实现步骤1. 使用嵌套列表推导式2. 使用itert

使用Docker构建Python Flask程序的详细教程

《使用Docker构建PythonFlask程序的详细教程》在当今的软件开发领域,容器化技术正变得越来越流行,而Docker无疑是其中的佼佼者,本文我们就来聊聊如何使用Docker构建一个简单的Py... 目录引言一、准备工作二、创建 Flask 应用程序三、创建 dockerfile四、构建 Docker

Python使用vllm处理多模态数据的预处理技巧

《Python使用vllm处理多模态数据的预处理技巧》本文深入探讨了在Python环境下使用vLLM处理多模态数据的预处理技巧,我们将从基础概念出发,详细讲解文本、图像、音频等多模态数据的预处理方法,... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核

Python使用pip工具实现包自动更新的多种方法

《Python使用pip工具实现包自动更新的多种方法》本文深入探讨了使用Python的pip工具实现包自动更新的各种方法和技术,我们将从基础概念开始,逐步介绍手动更新方法、自动化脚本编写、结合CI/C... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核