Python开发--fileinput

本文介绍了Python中的fileinput模块,该模块提供了同时读取多个文件的功能,并能够获取当前正在读取的文件名。通过示例代码展示了如何使用此模块读取文件内容及获取文件名。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转载自http://www.cnblogs.com/hongten/p/hongten_python_fileinput.html

python中,fileinput模块对读取文件操作提供了一些有用的方法

下面是我做的demo:

运行效果:

======================================

代码部分:

======================================

#python fileinput
'''
    fileinput:
    优点:
        可以同时读取多个文件
        可以获取到正在读取的文件的filename
        ....
    #######################################
    This module implements a helper class
    and functions to quickly write a loop
    over standard input or a list of files.
    If you just want to read or write one
    file see open().
    #正如API中所描述的一样:
    如果需要读/写文件推荐使用open()方法
'''

import fileinput
import os

def get_file_content(files):
    '''读取(多个)文件中的内容,以字符串的形式返回'''
    if files != None:
        lines = ''
        with fileinput.input(files) as fp:
            for line in fp:
                lines += line
            return lines
    else:
        print('files is None')

def get_file_name(file):
    '''只有文件被读的时候,才会取得filename,否则返回None'''
    if os.path.exists(file) and os.path.isfile(file):
        names = []
        for line in fileinput.input(file):
            name = fileinput.filename()
            if name != None:
                fileinput.nextfile()
            names.append(name)  
        return names
    else:
        print('the path [{}] is not exist!'.format(file))
        

def main():
    files = ('c:\\temp.txt', 'c:\\test.txt')
    file = 'c:\\temp.txt'
    content = get_file_content(files)
    print(content)
    name = get_file_name(file)
    print(name)

if __name__ == '__main__':
    main()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值