python中,fileinput模块对读取文件操作提供了一些有用的方法
下面是我做的demo:
运行效果:
======================================
代码部分:
======================================
1 #python fileinput
2 '''
3 fileinput:
4 优点:
5 可以同时读取多个文件
6 可以获取到正在读取的文件的filename
7 ....
8 #######################################
9 This module implements a helper class
10 and functions to quickly write a loop
11 over standard input or a list of files.
12 If you just want to read or write one
13 file see open().
14 #正如API中所描述的一样:
15 如果需要读/写文件推荐使用open()方法
16 '''
17
18 import fileinput
19 import os
20
21 def get_file_content(files):
22 '''读取(多个)文件中的内容,以字符串的形式返回'''
23 if files != None:
24 lines = ''
25 with fileinput.input(files) as fp:
26 for line in fp:
27 lines += line
28 return lines
29 else:
30 print('files is None')
31
32 def get_file_name(file):
33 '''只有文件被读的时候,才会取得filename,否则返回None'''
34 if os.path.exists(file) and os.path.isfile(file):
35 names = []
36 for line in fileinput.input(file):
37 name = fileinput.filename()
38 if name != None:
39 fileinput.nextfile()
40 names.append(name)
41 return names
42 else:
43 print('the path [{}] is not exist!'.format(file))
44
45
46 def main():
47 files = ('c:\\temp.txt', 'c:\\test.txt')
48 file = 'c:\\temp.txt'
49 content = get_file_content(files)
50 print(content)
51 name = get_file_name(file)
52 print(name)
53
54 if __name__ == '__main__':
55 main()