zoukankan      html  css  js  c++  java
  • python开发_fileinput

    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()
  • 相关阅读:
    python解析HTML的方法——HTMLParser
    使用python的nose模块进行测试
    python运行时修改代码的方法——monkey patch
    使用python的nose模块进行测试
    如何使用jquery是新tab形式
    table边框设置
    如何使用jquery是新tab形式
    table边框设置
    Notepad++安装Function list插件
    Notepad++安装Function list插件
  • 原文地址:https://www.cnblogs.com/hongten/p/hongten_python_fileinput.html
Copyright © 2011-2022 走看看