python - How to compare all lines in some file with another line? -
i new @ python , need help.
i have file x number of lines. want compare each line of file line, , write line file if different.
i looked answer didn't find can use. tried myself doesn't work.
my code:
filename = ... my_file = open(filename, 'r+') line in my_file: new_line = ("text") print line print new_line if new_line == line: print('same') else: print('diffrent') my_file.write('%s' % (new_line)) i want application write line file if doesn't exist there.
contents of filename ==================== text text1 text2 in case above new line "text", application shouldn't because line exist in file. however, if new line "text3" should written file follows:
contents of filename ==================== text text1 text2 text3
first, let's read contents of file can check if new line in there.
existing_lines = [line.rstrip('\n') line in open(filename, 'r')] let's have separate list named new_lines contains lines you'd check against file. can check see ones new follows:
new = [line line in new_lines if line not in existing_lines] these lines you'd append existing file:
with open(filename, 'a') f: [f.write(line + '\n') line in new]
Comments
Post a Comment