StringIO and compatibility with 'with' statement (context manager)

前端 未结 3 617
无人共我
无人共我 2020-12-23 16:41

I have some legacy code with a legacy function that takes a filename as an argument and processes the file contents. A working facsimile of the code is below.

What

3条回答
  •  被撕碎了的回忆
    2020-12-23 16:52

    you could define your own open function

    fopen = open
    def open(fname,mode):
        if hasattr(fname,"readlines"): return fname
        else: return fopen(fname,mode)
    

    however with wants to call __exit__ after its done and StringIO does not have an exit method...

    you could define a custom class to use with this open

    class MyStringIO:
         def __init__(self,txt):
             self.text = txt
         def readlines(self):
              return self.text.splitlines()
         def __exit__(self):
              pass
    

提交回复
热议问题