How to delete a line from a file using python -
i using following code find lines contains ':' special character. later trying remove lines file -
myfile = open('mypost.txt', 'rb') mytext = myfile.readlines() line in mytext: line.find(":") == "-1" if line.find(":"): is there function in python returns line character found (find() returns either -1 or location of searched character in line) or if use find() how delete lines value of find() -1?
using fileinput
optional in-place filtering: if keyword argument
inplace=1passedfileinput.input()orfileinputconstructor, file moved backup file , standard output directed input file (if file of same name backup file exists, replaced silently). makes possible write filter rewrites input file in place.
mypost.txt
abc de:f ghi import fileinput line in fileinput.input('mypost.txt', inplace=true): if ':' in line: continue # skip print line.rstrip('\n') # stdout redirected file mypost.txt
abc ghi the thing solution doesn't use .readlines() loads whole file memory, instead writes temporary file renamed original.
Comments
Post a Comment