Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- Testing ground for file input and output.
- Learning the fun way of course.
- == Changelog ==
- 6/18/13: Started. Timestamp() function created.
- 6/23/2013: After obnoxious amounts of fail, Timestamp() update works.
- """
- # Modules imported. datetime for Timestamp(), re for regex functions.
- from datetime import datetime
- import re
- # Global variables defined.
- Now = datetime.now() # really ugly format by default, so I prettied it in Timestamp().
- CurrentYear = Now.year
- CurrentMonth = Now.month
- CurrentDay = Now.day
- CurrentHour = Now.hour
- CurrentMinute = Now.minute
- CurrentSecond = Now.second
- # Timestamp function formats and prints current date and time.
- # Adds a new line, then the stamp, instead of smashing them together now.
- def Timestamp():
- Date = (str(CurrentMonth) + '/' + str(CurrentDay) + '/' + str(CurrentYear)) # month/day/year
- Time = (str(CurrentHour) + ':' + str(CurrentMinute) + ':' + str(CurrentSecond)) # hour:minute:seconds
- return "Last modified: " + str(Date) + " at " + str(Time)
- # Opens the test file to be used; creates it if it doesn't exist in proper directery.
- # 'a' is 'append'; adds data from file.write() to the end of file without overwriting.
- # 'w' will overwrite the entire freaking file. 'r' is read only, 'r+' is read+write.
- Test = open('test.txt', 'r+')
- # Checks if test.txt already contains a time stamp. If not, it is appended to the file.
- if re.search('Last modified: [\d]+/[\d]+/[\d]+ at [\d]+:[\d]+:[\d]+', Test.read()) == None:
- Test = open('test.txt', 'a')
- Test.write('\n' + str(Timestamp()))
- print("Timestamp added")
- Test = open('test.txt', 'r+')
- # Holy shit the timestamp updates :O
- OriginalFile = Test.read() # Original file before any edits.
- # Timestamp() format, to recognize and replace. [\d]+ means "At least one integer here"
- TestCompile = re.compile('Last modified: [\d]+/[\d]+/[\d]+ at [\d]+:[\d]+:[\d]+')
- # Original file + new Timestamp() edit.
- NewFile = re.sub(TestCompile, str(Timestamp()), OriginalFile)
- # Clears the entire file, because this appends a copy of entire file even though its not set to append.
- Test.write('')
- Test.close()
- Test = open('test.txt', 'r+')
- # Replace entire original file with the new, updated file.
- Test.write(NewFile)
- """
- ALWAYS make sure file is closed when finished.
- Python will write any and all file.write() data to a buffer, then the file,
- and only save the changes when file is closed. The code below closes then
- double checks closed status.
- """
- Test.close()
- if Test.closed == False:
- Test.close()
Advertisement
Add Comment
Please, Sign In to add comment