简体   繁体   English

如果 python 中的某些条件,则 Append 字符串到上一行

[英]Append string to previous line if certain condition in python

I have csv file with single column, in some cases the last value gets more space and create new row, here I need to find out and append it to the previous line我有单列的 csv 文件,在某些情况下,最后一个值会获得更多空间并创建新行,在这里我需要找出 append 它到上一行

for eg:例如: excel文件

my python code:我的 python 代码:

with open("01.csv", 'r+') as file:
    text = str()
    for line in file:
        if line[0:3] == "2021":
           text = "{} {}".format(text, line.strip())
        else:
             text = "{}\n{}".format(text, line.strip())
            
    file.seek(0)
    file.write(text[1:])

How to remove ||如何删除 || this in last and append next line to it in all occurrence.这在最后和 append 的下一行出现。

在此处输入图像描述

Line no 10 to be appended to line no 9 and line no 21 to be appended to line no 20 nd so on..第 10 行要附加到第 9 行,第 21 行要附加到第 20 行,依此类推。

You can't "append next line" if you haven't seen it yet.如果您还没有看到它,则不能“附加下一行”。 Your solution has to know that all appends are complete before otherwise acting on a line, which means you need to buffer the next line.您的解决方案必须知道所有附加都已完成,然后才能对一行进行操作,这意味着您需要缓冲下一行。

I think you're trying to re-compose the whole file in text as you go, which isn't a great model for file handling.我认为您正在尝试用text重新编写整个文件,这对于文件处理来说并不是一个很好的 model。 And if your test were working, the actions are actually the wrong way around - you want to include the newline when "20" starts the line.如果您的测试有效,那么这些操作实际上是错误的方式 - 您希望在“20”开始行时包含换行符。 I suggest that instead you write to another new file or simply correct the issue on the fly as below.我建议您改为写入另一个新文件或简单地立即纠正问题,如下所示。

with open("01.csv", 'r+') as file:
    complete_line = None
    for line in file:
        if complete_line is None:
           initial_action()
           complete_line = line
        elif line[0:2] == "20": # compatible with next 79 years
           act_on(complete_line)
           complete_line = line
        else:
           complete_line += line

    act_on(complete_line)        

where intial_action and act_on are functions for you to implement.其中intial_actionact_on是您要实现的功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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