转载自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()