The following code is supposed to be designed to find and eliminate leap year data. However, when it is ran, the code eliminates all of data in my February files. The good news is, each file has February 29th in them. So, how can I just find the month of February from the filename, then eliminate February’s 29th data and overwrite the same file it came from? I’m new to Python. Thanks!
for filename in filenames:
try:
with open(filename, ‘r’) as fid:
file_content = fid.readlines()
mo = re.search("(.[02]{2}_)",filename)
yr = re.search("(_[0-9]{4}",filename)
def leapyear(yr):
if N.remainder(yr,4):
yr = False
elif N.remainder(yr,100):
yr = True
if leapyear is True and mo == 2:
day = re.search('29',file_content)
N.array[day,:]
elif N.remainder(yr,400):
yr = False
else:
yr = True
output_file = filename +"_result.txt"
with open(output_file,'w') as fid:
fid.write(output_file)
fid.close()
except Exception as e:
print(f"error with {filename}: {e}")
Well, as the posted code is incomplete, it’s very difficult to give answers.
As an example, where is the function leapyear() called ? What is N ?
Anyway, the code has some issues.
re.search() returns None or a match object, not directly the matched value
leapyear() uses its single parameter both as an input value and a result, changing it from number to bool. This is generally a very bad practice in Python.
leapyear() should be changed to a function returning a bool value (i.e. instead of yr = False simply return False)
leapyear() uses a mix of parameters (yr) and global variables (N, leapyear, mo). Again, it’s not the best practice. It’s better to pass all external data as parameters
the function leapyear() tries to use a variabile with the same name, but it will refer to the function (as an object) instead.
elif N.remainder(yr,400): should appear before elif N.remainder(yr,100):, otherwise the 400-year exception will be ignored, because 400 is divisible by 100.
I fixed the issue with the code. I’m new to this forum. I didn’t know there was a leap year function, I used online sources to make the calculations as you see above. What is a bool value? Again, I need help with this code because I am completely new to Python.
for filename in filenames:
try:
with open(filename, ‘r’) as fid:
file_content = fid.readlines()
mo = re.search("(.[02]{2}_)",filename)
yr = re.search("(_[0-9]{4}",filename)
def leapyear(yr):
if N.remainder(yr,4):
yr = False
elif N.remainder(yr,400):
yr = False
elif N.remainder(yr,100):
yr = True
if leapyear is True and mo == 2:
day = re.search('29',file_content)
N.array[day,:]
else:
yr = True
output_file = filename +"_result.txt"
with open(output_file,'w') as fid:
fid.write(output_file)
fid.close()
except Exception as e:
print(f"error with {filename}: {e}")