Title: Action after writing to txt
Tags: python;variables
Question: Is there anyway I can check, once that the .txt file has been written? Is this able to be done with a while condition?
For example:
writetotxt = open(mytxt, 'w')
writetotxt.write('Line 1' + '\n')
writetotxt.write('Line 2')
writetotxt.close()
def txtwritten():
firstline = linecache.getline(mytxt, 1)
secline = linecache.getline(mytxt, 2)
check = firstline + secline
But, while the process, it returns a blank result. When it is finished writing to text file, then it displays line 1 and 2.
Can a for condition be set to determine whether it is finished writing to the txt?


Here is another answer: Also look at the flush() file method call and the buffering argument to open.
Two reasons that trying to read immediately after writing:
you're not opening the file to allow reading (need to open with mode w+ to allow reading)
files are buffered by default: calls to write() add to the buffer; until the buffer fills up, a flush() call is made, or the file is closed, the contents of the buffer will not actually be written to disk.

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2016:00:09/09/16', 'FavoriteCount': 1.0, 'PostTypeId': 1, 'Tags': '<python><variables>', 'Title': 'Action after writing to txt', 'ViewCount': 56, 'id': 39403809, 'user_AboutMe': None, 'user_AccountId': 8718948.0, 'user_DisplayName': 'Dzrte4gle', 'user_Reputation': 49.0, 'user_Views': 8.0, 'user_id': 6522663.0}}