1

I have some text like this:

<Row 1 Having A Text>
<Row 2 Having B Text>
<Row 3 Having C Text>

I am trying to remove entirely and shift up.

I have been trying to use this:

for line in fileinput.input(new_name, inplace=True): 
print (re.sub(r'<Row 2.*[\r\n]*', '', line.strip()))

However, this just results in the following:

<Row 1 Having A Text>

<Row 3 Having C Text>

And Row 3 does not move up. What am I missing here?

curioustea
  • 13
  • 2

2 Answers2

3

Your problem is that even though your regex matches and replaces the contents of line with an empty string (''), print('') will output a blank line. Instead of printing every line, print just the lines that don't start with <Row 2

for line in fileinput.input(new_name, inplace=True): 
    if not line.strip().startswith('<Row 2'):
        print(line)
Nick
  • 138,499
  • 22
  • 57
  • 95
  • Thanks for the help. I tried doing this but now I am running into an issue where I have this error: UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 7725: character maps to What are the possible workarounds for inplace and encoding in fileinput? – curioustea Jun 01 '20 at 22:58
  • @curioustea this might help: https://stackoverflow.com/questions/9233027/unicodedecodeerror-charmap-codec-cant-decode-byte-x-in-position-y-character – Nick Jun 01 '20 at 23:07
  • Thank you Nick. I was able to get to a workaround eventually regarding that matter. Selecting your comment as the answer since it answered my initial question. – curioustea Jun 03 '20 at 23:45
  • @curioustea I'm glad you got it resolved. If you couldn't find a solution on SO, it might be worth asking and self-answering a question on it. and thanks... – Nick Jun 03 '20 at 23:47
0

print() outputs the LF even if the content is empty, so you replace 'Row 2' with an empty string, but since you still use print, you get an empty line on output.

You may check for an empty line:

for line in fileinput.input(new_name, inplace=True): 
    output = re.sub(r'<Row 2.*[\r\n]*', '', line.strip())
    if len(output) :
        print(output)
lenik
  • 23,228
  • 4
  • 34
  • 43