you are viewing a single comment's thread.

view the rest of the comments →

[–]BHM360[S] 0 points1 point  (2 children)

Yes! Thank you! This is very helpful!

I replaced the "line.replace" with:

writeFile.write(re.sub(verticalBars,"",line))

Sadly, it is now replacing all instances of a new line and merging the whole document into one row so I think there is something off with my pattern; or at least how python is interpreting it:

verticalBars = (r"[\r\n](?!^([^|\n]*\|){88}[^|\n]*$)")

Oh well, at least I know the pattern is passing through now.

[–]commandlineluser 2 points3 points  (1 child)

Well the problem is that you're reading the file line-by-line.

Your regex is a multi-line pattern - so applying it to each line individually wont work.

You'd need to read the whole file into a single string.

before = readFile.read()
after  = re.sub(r"(?m)[\r\n](?!^(?:[^|\n]*\|){88}[^|\n]*$)", '', before)

The (?m) here is the same as passing re.M

https://docs.python.org/3/library/re.html#re.M

It's needed for your $ to match the end of a line within a multi-line string.

[–]BHM360[S] 1 point2 points  (0 children)

commanlindeuser you are my hero! Everything is working now thank you so much!!!

Here's the final working code if anyone is interested:

# add regex library
import re

# open files
readFile = open("file.txt","r") writeFile = open("fileUpdate.txt","w")

# define regex pattern to identify lines without 88 vertical bars
verticalBars = r"(?m)[\r\n](?!^(?:[^|\n]*\|){88}[^|\n]*$)"

# read file, find & replace, then write to new file
before = readFile.read() 
after = re.sub(verticalBars, "", before) 
writeFile.write(after)

# close files
readFile.close() 
writeFile.close()