4 回答

TA貢獻(xiàn)1995條經(jīng)驗(yàn) 獲得超2個(gè)贊
您沒(méi)有提供示例數(shù)據(jù),但我認(rèn)為這可能有效:
filepath = "C:/Bg_Log/KLBG04.txt"
with open(filepath) as fp:
lines = fp.read().splitlines()
with open(filepath, "w") as fp:
for line in lines:
ln = "KLBG04 " + line + " " + line[18] # current column order
sp = ln.split() # split at spaces
dt = '/'.join(sp[1].split('/')[::-1]) # reverse date
print(sp[0],dt,sp[3],sp[-1],sp[-2]) # new column order
# print("KLBG04",line,line[18], file=fp)

TA貢獻(xiàn)1111條經(jīng)驗(yàn) 獲得超0個(gè)贊
試試這個(gè)`
for line in lines:
words = line.split() # split every word
date_values = words[0].split('/') # split the word that contains date
#create a dictionary as follows
date_format = ['YY','DD','MM']
date_dict = dict(zip(date_format, date_values))
#now create a new variable with changed format
new_date_format = date_dict['MM'] + '/' + date_dict['DD'] + '/' + date_dict['YY']
print(new_date_format)
#replace the first word [index 0 is having date] with new date format
words[0] = new_date_format
#join all the words to form a new line
new_line = ' '.join(words)
print("KLBG04",new_line,line[18])
`

TA貢獻(xiàn)1946條經(jīng)驗(yàn) 獲得超3個(gè)贊
先嘗試split()該行,然后按您想要的順序打印列表
from datetime import datetime # use the datetime module to manipulate the date
filepath = "C:/Bg_Log/KLBG04.txt"
with open(filepath) as fp:
lines = fp.read().splitlines()
with open(filepath, "w") as fp:
for line in lines:
date, time, venue = line.split(" ") # split the line up
date = datetime.strptime(date, '%y/%m/%d').strftime('%d/%m/%y') # format your date
print("KLBG04", date, venue, venue[0], time, file=fp) # print in your desired order

TA貢獻(xiàn)1817條經(jīng)驗(yàn) 獲得超6個(gè)贊
為什么不將輸出存儲(chǔ)為字符串本身,并使用該split()方法在每個(gè)空格處拆分字符串,然后對(duì)索引 1 (將包含日期的索引)使用另一個(gè)拆分方法,并在每個(gè)空格處再次拆分它/(所以然后您可以操縱日期)。
for line in lines:
String output ="KLBG04",line,line[18], file=fp # Rather than printing store the output in a string #
x = output.split(" ")
date_output = x[1].split("/")
# Now you can just manipulate the data around and print how you want to #
添加回答
舉報(bào)