There is a variable name_elem_site , the value of which must be written to the file. The value obtained from a third-party source.

There is a file, initially empty.

It is necessary to add the value of the variable name_elem_site to this file on a new line, but only if the value of the variable does not coincide with the last line of this file.

For example, if the lines come in successively:

 Текст Текст Текст Текст2 Текст Текст3 Текст2 Текст 

That file is written only

 Текст Текст2 Текст Текст3 Текст2 Текст 

because there were three consecutive identical values, and this is prohibited.

  • 2
    If the program runs continuously, save the previous value and compare with the new one before recording. If it writes only one line for all its work, then we read the file, select the last line and compare. Where do you have a problem? - user194374
  • @kff in check on the last line. - J. Doe

3 answers 3

Read the last line from the file.


First option. Simplest. But the file must fit entirely into memory. In the case of an empty file does not work correctly.

 with open('test.txt') as file: last_line = file.readlines()[-1].strip() 

(We read all the lines of the file in the list, take the last one, remove the newline character, if it exists.)


The second option. A little harder. But does not require memory to store the entire file. In the case of an empty file also works incorrectly.

 with open('test.txt') as file: for last_line in file: pass last_line = last_line.strip() 

(We read the file line by line. In the variable, the last read line is saved. Then again, we delete the newline character, if there is one.)


The third option. It is similar to the first, but it works correctly in the case of an empty file. In this case, the last_line will contain the value None .

 last_line = None with open('test.txt') as file: lines = file.readlines() if lines: last_line = lines[-1].strip() 

Fourth option. It is similar to the second, but it works correctly in the case of an empty file. In this case, the last_line will contain the value None .

 last_line = None with open('test.txt') as file: for last_line in file: pass if last_line: last_line = last_line.strip() 
  • Oh, thank you! I will go to try in practice + check for the contract the same data will check at the same time. - J. Doe
  • one
    If the file in memory does not fit, it is better to search from the end of '\n' find the last line , rather than going through the file ( deque(file, maxlen=1) ). For example, if the mmap file is like s : i = s.rfind(b'\n', 0, -1); last_line = (s[i+1:] if i != -1 else s).decode() i = s.rfind(b'\n', 0, -1); last_line = (s[i+1:] if i != -1 else s).decode() . You can still file.seek() , but the code is more complicated - jfs
 def elem_write(name_elem_site: str, file='test.txt', last_line=''): with open(file) as fr, open(file, 'a') as fa: for last_line in fr:pass if not last_line.rstrip() == name_elem_site: print(name_elem_site, file=fa) 

    To write strings to a file so that adjacent values ​​do not repeat, you can use itertools.groupby() :

     #!/usr/bin/env python3 from itertools import groupby lines = ['Текст','Текст','Текст', 'Текст2', 'Текст', 'Текст3', 'Текст2', 'Текст'] with open('uniq_just_seen.txt', 'w') as file: # start with empty file file.writelines(line + '\n' for line, _ in groupby(lines)) 

    Result in uniq_just_seen.txt file

     Текст Текст2 Текст Текст3 Текст2 Текст 

    Instead of the lines list, you can use an arbitrary collection, for example, lines read from standard input: lines = map(str.strip, sys.stdin) or counted by some algorithm:

     import random def generate_lines(choices): while random.random() < 0.9: # 10% to exit yield random.choice(choices) lines = generate_lines(['Текст', 'Текст2', 'Текст3'])