亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將行存儲到數組中并逐行打印

將行存儲到數組中并逐行打印

藍山帝景 2024-01-04 10:20:46
當前代碼: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:            print("KLBG04",line,line[18], file=fp)輸出:KLBG04 20/01/03 08:09:13 G0001 G需要靈活地移動列并使用數組或列表操作日期,如下所示KLBG04 03/01/20 G0001 G 08:09:13
查看完整描述

4 回答

?
拉風的咖菲貓

TA貢獻1995條經驗 獲得超2個贊

您沒有提供示例數據,但我認為這可能有效:


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)


查看完整回答
反對 回復 2024-01-04
?
catspeake

TA貢獻1111條經驗 獲得超0個贊

試試這個`


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])

`


查看完整回答
反對 回復 2024-01-04
?
智慧大石

TA貢獻1946條經驗 獲得超3個贊

先嘗試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



查看完整回答
反對 回復 2024-01-04
?
慕的地6264312

TA貢獻1817條經驗 獲得超6個贊

為什么不將輸出存儲為字符串本身,并使用該split()方法在每個空格處拆分字符串,然后對索引 1 (將包含日期的索引)使用另一個拆分方法,并在每個空格處再次拆分它/(所以然后您可以操縱日期)。



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 #


查看完整回答
反對 回復 2024-01-04
  • 4 回答
  • 0 關注
  • 220 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號