(Nov-07-2022, 08:51 PM)deanhystad Wrote: [ -> ]I think it is a logic error. I can think of no reason why you would open a file and write contents only to have them overwritten. Some sort of default file content? Two things make me think the code is a logic error.
1. The file open modes don't make any sense.
2. I think I know what they are trying to do and they did it wrong.
There is no reason to open the file using mode="a". You just opened the file using mode="w" and have done no writes. The file is empty. Why open with mode="a"? This code works exactly the same on my windows computer as the original code that used mode="a".
def CreateFile(FilePath):
file = open(FilePath, 'w')
header=["Court", "Location", "Citation Number", "Case Description","File Date"]
with open(FilePath, 'w',encoding="utf-8",newline="") as f:
writer = csv.writer(f)
writer.writerow(header)
return file
Opening the file with mode = "a" gives the impression that the file has content and the new write will appear after the existing content. There cannot be any content in the file because it was wiped out by the open two lines above with mode = "w".
One of the file opens sets the newline and the other doesn't. Setting the newline = "" is a fix for an annoying behavior csv_writer has on windows machines. From the csv documentation.
Quote:If newline='' is not specified, newlines embedded inside quoted fields will not be interpreted correctly, and on platforms that use \r\n linendings on write an extra \r will be added. It should always be safe to specify newline='', since the csv module does its own (universal) newline handling
This makes me think the purpose of the code is to open the file using newline="" so the header can be written without writing the extra \r on windows machines. Then the file is re-opened without setting newline so it can be written by other code that doesn't behave the same way as csv.writer.
If that is the case, the code should be written like this:
def CreateFile(FilePath):
# Opening file with newline="" to avoid extra \r that csv.writer adds on windows machines
header=["Court", "Location", "Citation Number", "Case Description","File Date"]
with open(FilePath, 'w', encoding="utf-8", newline="") as f:
writer = csv.writer(f)
writer.writerow(header)
# Reopen file for appending without newline=""
return open(FilePath, 'a', encoding="utf-8")
Well, really it should be written like this:
import contextlib
@contextlib.contextmanager
def CreateFile(FilePath, encoding="utf-8"):
file = open(FilePath, 'w', encoding=encoding)
file.write("Court,Location,Citation Number,Case Description,File Date\n")
yield file
file.close()
Now you can do this:
with CreateFile("C:/working/access/md/maryland/Maryland Case Search.csv") as file:
# do stuff with file
# File automatically closes when leaving context
I like both solutions. The first is the clearer one until one understands the concept of context managers