fileinput模块读取文件「建议收藏」

fileinput模块读取文件「建议收藏」fileinput模块可以对一个或多个文件中的内容进行迭代、遍历等操作。该模块的input()函数有点类似文件readlines()方法,区别在于前者是一个迭代对象,需要用for循环迭代,后者是一次性读取所有行。用fileinput对文件进行循环遍历,格式化输出,查找、替换等操作,非常方便。【典型用法】importfileinputforlineinfileinput.input…

大家好,又见面了,我是你们的朋友全栈君。

fileinput模块可以对一个或多个文件中的内容进行迭代、遍历等操作。该模块的input()函数有点类似文件

readlines()方法,区别在于前者是一个迭代对象,需要用for循环迭代,后者是一次性读取所有行。

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

【典型用法】

import fileinput
for line in fileinput.input():
process(line)
【基本格式】

fileinput.input([files[, inplace[, backup[, bufsize[, mode[, openhook]]]]]])

【默认格式】

fileinput.input (files=None, inplace=False, backup=’’, bufsize=0, mode=‘r’, openhook=None)

files: #文件的路径列表,默认是stdin方式,多文件[‘1.txt’,‘2.txt’,…]
inplace: #是否将标准输出的结果写回文件,默认不取代
backup: #备份文件的扩展名,只指定扩展名,如.bak。如果该文件的备份文件已存在,则会自动覆盖。
bufsize: #缓冲区大小,默认为0,如果文件很大,可以修改此参数,一般默认即可
mode: #读写模式,默认为只读
openhook: #该钩子用于控制打开的所有文件,比如说编码方式等;

【常用函数】

复制代码
fileinput.input() #返回能够用于for循环遍历的对象
fileinput.filename() #返回当前文件的名称
fileinput.lineno() #返回当前已经读取的行的数量(或者序号)
fileinput.filelineno() #返回当前读取的行的行号
fileinput.isfirstline() #检查当前行是否是文件的第一行
fileinput.isstdin() #判断最后一行是否从stdin中读取
fileinput.close() #关闭队列
复制代码
【常见例子】

例子01: 利用fileinput读取一个文件所有行

复制代码

import fileinput
for line in fileinput.input(‘data.txt’):
print line,
#输出结果
Python
Java
C/C++
Shell
复制代码
命令行方式:

复制代码
#test.py
import fileinput

for line in fileinput.input():
print fileinput.filename(),’|’,‘Line Number:’,fileinput.lineno(),’|: ‘,line

c:>python 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
复制代码
例子02: 利用fileinput对多文件操作,并原地修改内容

复制代码
#test.py
#—样本文件—
c:Python27>type 1.txt
first
second

c:Python27>type 2.txt
third
fourth
#—样本文件—
import fileinput

def process(line):
return line.rstrip() + ’ line’

for line in fileinput.input([‘1.txt’,‘2.txt’],inplace=1):
print process(line)

#—结果输出—
c:Python27>type 1.txt
first line
second line

c:Python27>type 2.txt
third line
fourth line
复制代码
命令行方式:

复制代码
#test.py
import fileinput

def process(line):
return line.rstrip() + ’ line’

for line in fileinput.input(inplace = True):
print process(line)

#执行命令
c:Python27>python test.py 1.txt 2.txt
复制代码
例子03: 利用fileinput实现文件内容替换,并将原文件作备份

复制代码
#样本文件:
#data.txt
Python
Java
C/C++
Shell

#FileName: test.py
import fileinput

for line in fileinput.input(‘data.txt’,backup=’.bak’,inplace=1):
print line.rstrip().replace(‘Python’,‘Perl’) #或者print line.replace(‘Python’,‘Perl’),

#最后结果:
#data.txt
Python
Java
C/C++
Shell
#并生成:
#data.txt.bak文件
复制代码
例子04: 利用fileinput将CRLF文件转为LF

复制代码
import fileinput
import sys

for line in fileinput.input(inplace=True):
#将Windows/DOS格式下的文本文件转为Linux的文件
if line[-2:] ==
:
line = line +

sys.stdout.write(line)

复制代码
例子05: 利用fileinput对文件简单处理

复制代码
#FileName: test.py
import sys
import fileinput

for line in fileinput.input(r’C:Python27info.txt’):
sys.stdout.write(’=> ‘)
sys.stdout.write(line)

#输出结果

=> The Zen of Python, by Tim Peters
=>
=> Beautiful is better than ugly.
=> Explicit is better than implicit.
=> Simple is better than complex.
=> Complex is better than complicated.
=> Flat is better than nested.
=> Sparse is better than dense.
=> Readability counts.
=> Special cases aren’t special enough to break the rules.
=> Although practicality beats purity.
=> Errors should never pass silently.
=> Unless explicitly silenced.
=> In the face of ambiguity, refuse the temptation to guess.
=> There should be one– and preferably only one –obvious way to do it.
=> Although that way may not be obvious at first unless you’re Dutch.
=> Now is better than never.
=> Although never is often better than right now.
=> If the implementation is hard to explain, it’s a bad idea.
=> If the implementation is easy to explain, it may be a good idea.
=> Namespaces are one honking great idea – let’s do more of those!
复制代码
例子06: 利用fileinput批处理文件

复制代码
#—测试文件: test.txt test1.txt test2.txt test3.txt—
#—脚本文件: test.py—
import fileinput
import glob

for line in fileinput.input(glob.glob(test*.txt)):
if fileinput.isfirstline():
print ‘-’*20, ‘Reading %s…’ % fileinput.filename(), ‘-’*20
print str(fileinput.lineno()) + ‘: ’ + line.upper(),

#—输出结果:

——————– Reading test.txt… ——————–
1: AAAAA
2: BBBBB
3: CCCCC
4: DDDDD
5: FFFFF
——————– Reading test1.txt… ——————–
6: FIRST LINE
7: SECOND LINE
——————– Reading test2.txt… ——————–
8: THIRD LINE
9: FOURTH LINE
——————– Reading test3.txt… ——————–
10: THIS IS LINE 1
11: THIS IS LINE 2
12: THIS IS LINE 3
13: THIS IS LINE 4
复制代码
例子07: 利用fileinput及re做日志分析: 提取所有含日期的行

复制代码
#–样本文件–
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…
复制代码
例子08: 利用fileinput及re做分析: 提取符合条件的电话号码

复制代码
#—样本文件: phone.txt—
010-110-12345
800-333-1234
010-99999999
05718888888
021-88888888

#—测试脚本: test.py—
import re
import fileinput

pattern = ‘[010|021]-d{8}’ #提取区号为010或021电话号码,格式:010-12345678

for line in fileinput.input(‘phone.txt’):
if re.search(pattern,line):
print ‘=’ * 50
print ‘Filename:’+ fileinput.filename()+’ | Line Number:’+str(fileinput.lineno())+’ | ‘+line,

#—输出结果:—

==================================================
Filename:phone.txt | Line Number:3 | 010-99999999

Filename:phone.txt | Line Number:5 | 021-88888888

复制代码
例子09:利用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.* fileinput *.py
复制代码
例子10:利用fileinput做正则替换

复制代码
#—测试样本: input.txt

  • [Learning Python](#author:Mark Lutz)

#—测试脚本: test.py

import fileinput
import re
  
for line in fileinput.input():
    line = re.sub(r'* [(.*)](#(.*))', r')

转自https://www.cnblogs.com/jinjiangongzuoshi/p/5637793.html

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/137971.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • leetcode最长回文子串_kmp算法题

    leetcode最长回文子串_kmp算法题实现 strStr() 函数。给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。示例 1:输入: haystack = “hello”, needle = “ll”输出: 2示例 2:输入: haystack = “aaaaa”, needle = “bba”输出: -1说明:当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题

    2022年8月9日
    4
  • jenkins拉取gitlab代码_查看git仓库地址

    jenkins拉取gitlab代码_查看git仓库地址前言python自动化的脚本开发完成后需提交到git代码仓库,接下来就是用Jenkins拉取代码去构建自动化代码了新建项目打开Jenkins新建一个自由风格的项目源码管理Repository

    2022年8月6日
    5
  • Leptonica在VS2010中的编译及简单使用举例

    Leptonica在VS2010中的编译及简单使用举例

    2022年2月6日
    38
  • ES集群搭建「建议收藏」

    ES集群搭建「建议收藏」1.设置内核参数:/etc/sysctl.confvm.max_map_count=6553602.设置文件描述符限制:/etc/security/limits.conf*softnofile65536*hardnofile131072*softnproc2048*hardnproc4096&&1和2的配置,可以等到启动时候报错,再修改(可以清晰地知道1、2在处理什么问题)3.es不允许root用户启动,修改用户和分组chownuser1.

    2022年10月13日
    2
  • BoundsChecker使用说明(代码调试)

    目录….1一、BoundsChecker简介….2二、安装环境….2三、BoundsChecker两种工作模式….3      3.1ActiveCheck..3      3.2FinalCheck..3四、特性和优点….5五、检测示例….65.1内存泄漏检测示例….65.2野指针检测示

    2022年4月17日
    41
  • Linux磁盘阵列

    Linux磁盘阵列一、磁盘阵列1基础知识磁盘阵列(RedundantArraysofIndependentDisks,RAID),有“独立磁盘构成的具有冗余能力的阵列”之意。磁盘阵列是由很多价格较便宜的磁盘,以硬件(RAID卡)或软件(MDADM)形式组合成一个容量巨大的磁盘组,利用多个磁盘组合在一起,提升整个磁盘系统效能。利用这项技术,将数据切割成许多区段,分别存放在各个硬盘上。磁盘阵列还能利用同位检查(ParityCheck)的观念,在数组中任意一个硬盘故障时,仍可读出数据,在数据重构时,将数据经计算

    2022年5月25日
    36

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号