Nov-07-2022, 06:15 PM
(This post was last modified: Nov-07-2022, 06:15 PM by deanhystad.)
While answering a question in another thread I wrote this:
import contextlib @contextlib.contextmanager def CreateFile(FilePath): file = open(FilePath, 'w', encoding="utf-8") file.write("Court,Location,Citation Number,Case Description,File Date\n") yield file file.close()I occasionally create context managers when writing code that requires "cleaning up", but I never did it for a file. To use the code above, I am forced to us a context manager:
with CreateFile(filename) as file: # do stuff with fileI cannot do this because CreateFile creates a context object, not a file:
file = CreateFile(filename)So how does open() let me do this?
file_one = open(filelename_one) with open(filename_two) as file_two: # do file_two stuffThe best I can do to mimic open() is this:
class CreateFile(): def __init__(self, filename, mode="w", encoding="utf-8"): print(f"CreateFile({filename})") self.file = open(filename, mode, encoding=encoding) self.file.write("Court,Location,Citation Number,Case Description,File Date\n") def __enter__(self): print("enter") return self.file def __exit__(self, *_): print("exit") self.file.close() def __getattr__(self, attribute): print(f"__getattr__({attribute})") return getattr(self.file, attribute) file = CreateFile("junk.txt") file.write("This is a test\n") print(file.tell()) file.close() print("\n") with CreateFile("junk2.txt") as file: file.write("This is a test\n")
Output:CreateFile(junk.txt)
__getattr__(write)
__getattr__(tell)
75
__getattr__(close)
CreateFile(junk2.txt)
enter
exit