我正在尝试创建一个将日期格式从dd / mm / yy更改为mm / dd / yy的程序。它将读取一个文件,并应将第一种格式的日期替换为第二种格式。
#input file
filePath='..\\Test.txt'
lines = []
with open (filePath, "r") as readMyFile:
with open(filePath,"w") as writeMyFile:
#for each line in the input file
for line in readMyFile:
day=''
month=''
year=''
oldDate=''
newDate=''
hour=''
min=''
sec=''
oldTime=''
newTime=''
if 'Date=' in line:
i=0
while line[i] !=';':
if line[i] == '=':
day=line[i+1]+line[i+2]
month=line[i+4]+line[i+5]
year=line[i+7]+line[i+8]
oldDate=day+'/'+month+'/'+year
newDate=month+'/'+day+'/'+year
i=i+1
lines.append(line)
#read replace the string and write to output file
line=line.replace(oldDate, newDate)
writeMyFile.write(line)
if "Time=" in readMyFile:
i=0
while line[i] != ';':
if line[i] == '=':
hour=line[i+1]+line[i+2]
min=line[i+4]+line[i+5]
sec=line[i+7]+line[i+8]
oldTime=hour+':'+min+':'+sec
if hour > 12:
newTime=(hour-12)+':'+min+':'+sec
line=line.replace(oldTime, newTime)
writeMyFile.write(line)
i=i+1
writeMyFile.close()
#close input and output files
readMyFile.close()
我不知道为什么,但是程序末尾的txt文件为空。 你能帮助我吗?谢谢
P.S:例如,txt文件中的行将不同:
Date = 11/09/20; 时间= 09:15:16; exampleLine1 exampleLine2 .. exampleLineN ..
Date = 25/11/20; 时间= 15:15:16; exampleLine1 exampleLine2 .. exampleLineN .. ...