简体   繁体   中英

How to replace the last line ina text file?

I have a program that runs twice a day however I am rewriting it as I'm making a new update for my program. I'm running into a problem. The program writes about 2500 different text files each time it runs.

Each file is a csv and has five columns date, data, data, data, data

Im wanting to delete the last row of the data to write the new information only if it has already ran that day.

with open('file.csv', 'r+') as file:
    info = [line.split(',') for line in file]
    for row in info:
        if str(today) in row:
            #need help here

this is the old one that I'm re-doing. I need to rework it as it will no longer work with the new program.

with open('file.csv', 'a+') as file:
    file.write(str(today) + ',' +
               str(data) + ',' +
               str(data) + ',' +
               str(data) + ',' +
               str(data) + ',' + '\n')

Maybe this will help you

with open('file.csv', 'r+') as file:
    info = [line.split(',') for line in file]
for idx, row in enumerate(info):
    if str(today) in row:
        # replace with new today data
        info[idx] = [str(today), str(data), str(data), str(data), str(data)]

with open('file.csv', 'w+') as file:
    for row in info:
        file.write(str(today) + ',' +
                   str(data) + ',' +
                   str(data) + ',' +
                   str(data) + ',' +
                   str(data) + ',' + '\n')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM