为了账号安全,请及时绑定邮箱和手机立即绑定

将行存储到数组中并逐行打印

将行存储到数组中并逐行打印

蓝山帝景 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 关注
  • 137 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信