I've made a program that can scan through a plain text document for the string "SA001:" and if it's not there, it ads it in at the top. But the problem comes with the saving to the document: It adds some things to the document that I don't know how to get rid of (to see what i mean, point the program to any txt file, tell it to modify it, and then look at the output. ) Also, I'd like it to print a carriage return to the txt file, which I don't know how to do...
Heres the code:
import pickle
import random
saFlag = False #<--- flag
saLessFile = raw_input("File to scan? ")
#opens the selected file
textf = open(saLessFile, 'r')
str1 = textf.read()
textf.close()
#makes every word in file a list
wordlist = str1.split(None)
for i in range(0, len(wordlist)):
print wordlist[i],
print "\n\nScan loop follows:"
for i in range(0, len(wordlist)):
if (wordlist[i].lower() == "sa001:"):
print "SA001 found:"
saFlag = True
for j in range(i, (i+7)):
print wordlist[j],
print "..."
if saFlag:
print "No altering needed\n"
else:
print "SA not found turn document into the following?"
wordlist.insert(0, "SA001: This is a test, blah blah blah blah blah!\n")
#turns the list into a string with a space inbetween each word
joinList = " ".join(wordlist)
print joinList
#asks user if they are sure they wish to modify
sure = raw_input("Modify?(y or n): ")
if sure == "y" or sure == "Y":
#saves the new string over the old file's words, essentially modifying the contents
file = open(saLessFile, "w")
pickle.dump(joinList, file)
file.close()
print "modified..."
elif sure == "n" or sure == "N":
quit