MidNight
MidNight

Reputation: 1

Remove specific character in a line from a text file

My text file is:

CREATE TABLE `redirect` (
`rd_from` int(8) unsigned NOT NULL DEFAULT 0,
`rd_namespace` int(11) NOT NULL DEFAULT 0,
`rd_title` varbinary(255) NOT NULL DEFAULT '',
`rd_interwiki` varbinary(32) DEFAULT NULL,
`rd_fragment` varbinary(255) DEFAULT NULL,
PRIMARY KEY (`rd_from`),
KEY `rd_ns_title` (`rd_namespace`,`rd_title`,`rd_from`)
) ENGINE=InnoDB DEFAULT CHARSET=binary ROW_FORMAT=COMPRESSED;

My goal is to remove the text, which is:

,
PRIMARY KEY (`rd_from`),  

I am using this code (PYTHON) (does not accomplish my goal). Your help is highly valued.:

with open('filepath.txt', 
                mode = "r", errors='ignore') as file:

    with open("filepath.txt", mode = "w", errors='ignore') as newfile:
             
            badline = [",\nPRIMARY KEY (`rd_from`),"]
            for lines in file:     
                for word in badline:
                 lines = lines.replace(word, ' ')
                newfile.write(lines) 

Upvotes: 0

Views: 416

Answers (1)

Adam Smooch
Adam Smooch

Reputation: 1322

with file.readlines() you'll need to loop over the lines, and your search for badline will not match anything, since the lines break at each \n.

Instead you could use file.read() to get a single string:

badline = "\nPRIMARY KEY (`rd_from`),"

with open('filepath.txt', mode = "r", errors='ignore') as file:
  remaining = file.read().replace(badline, '')

with open("filepath.txt", mode = "w", errors='ignore') as newfile:
  newfile.write(remaining)

Furthermore, if you remove both the preceding and the following , you may be breaking your file-content's syntax:

badline = [",'\nPRIMARY KEY (`rd_from`),"]

becomes

badline = "\nPRIMARY KEY (`rd_from`),"

...or read up on the command-line tool sed 🤷‍♂️

Upvotes: 1

Related Questions