简体   繁体   中英

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) 

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 🤷‍♂️

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