Nov-07-2022, 01:36 AM
I am looking at some code someone else wrote in which open is used then again on the same file that is already open. In VB, another language I use, something like this would raise an error and be denied. My main question is, what is the reason for the double opening, as you'll see in the following snippets
def CreateFile(FilePath): file = open(FilePath, 'w') header=["Court", "Location", "Citation Number", "Case Description","File Date"] with open(FilePath, 'a',encoding="utf-8",newline="") as f: writer = csv.writer(f) writer.writerow(header) return file
filepath="C:\working\access\md\maryland" filename='Maryland Case Search.csv' fullpath=os.path.join(filepath,filename) if (os.path.exists(fullpath)==False): file=CreateFile(fullpath)Is a new instance of the file open in the 'with open' call or does it create a pointer to the previously opened instance? I suppose If only the with call was used the file would have closed when the function ends. If that's the reason for the first call to open, why couldn't that have used all the necessary arguments, write the header, then return?