In the script, for each text file, I check the first two characters. If the first two characters are "[{" which means it is a JSON file, then execute other codes.
However, I have to read the file twice with open(f, 'r', encoding = 'utf-8', errors='ignore' as infile:
, which is duplicated. Is there any better way to write this code?
result = []
for f in glob.glob("D:/xxxxx/*.txt"):
print("file_name: ",f)
with open(f, 'r', encoding = 'utf-8', errors='ignore') as infile:
first_two_char = infile.read(2)
print(str(first_two_char ))
if first_two_char == "[{":
with open(f, 'r', encoding = 'utf-8', errors='ignore') as infile:
json_file = json.load(infile, strict=False)
print(len(json_file))
result.append(json_file) #here appending the list with Jason content
print(len(result))