Please give an example. need a cycle with a postcondition. In which the array is read lines from a file, line by line. Array: mas_text = [] File from where it will be read: text_file

Thank.

  • A “post-conditional loop” is do {...} while (...) in C? If so, break off. - alexlz
  • Yes, there is no linguistic construction, but what's stopping it from resolving it logically? - spirit

2 answers 2

 for line in file.xreadlines(): do_smth() post_condition() 

UPD:

 mas_text = [line for line in text_file.xreadlines()] 

UPD2: but the beautiful version with the condition, but not the fact that this is what the topstarter needs:

 mas_text = [post_condition(line) and line for line in text_file.xreadlines()] 

Well, the post-condition can be made an anonymous function, but the EOT already need to specifically look at what you need to do.

  • and if you just need to push all the rows into an array, then nothing is simpler than text = f.readlines (). True, there is a nuance with the newline character (it remains everywhere) - it is often not needed. And if it is not needed, then the easiest way is to use the following method: text = f.read (). Splitlines () - R_cassum
  • >> and if you just need to drive all the rows into the array, then nothing is easier than what makes you think so? Why load the entire file into memory if you can carefully iterate through it? - actionless
  • +1 Probably even more Python would use the map . - VladD
  • @VladD can, after all, not a map, but a list generator? for example: mas_text = [line for line in text_file.xreadlines ()] although it seems to me that it looks somehow crooked and you can make it even easier to write your own version with map? - actionless
  • a person needs a post-condition, and you began to talk about the beauty of transferring a file to an array. - spirit

Why do you need a post-condition to stop somewhere? then so, given the above:

 # -*- coding: utf-8 -*- def file2list(text_file): try: f = open(text_file) except IOError: print "file %s not exist" %text_file return 1 #если просто до конца файла mas_text = f.readlines() # конец моего первого если # если при этом условия mas_text = [] for line in f.xreadlines(): if line == "начиная с этой не считывать\n": f.close() return mas_text mas_text.append(line) if line == "после этой не считывать\n": f.close() return mas_text # конец моего второго если f.close() return mas_text if __name__ == "__main__": mas_text = file2list("/tmp/file") print mas_text 

Checked, at the end of lines it is necessary '\ n'