I need to read from file, two strings, one 'static' string from file, and one random dynamically generated one, which is also written on a file.
Then, replace one character in the random generated string with another random one.
And repeat the process. Until I get the "static" string which is on a file, in this case "THIS IS A STRING".
I'm pretty lost trying to achieve this, this is what I have so far:
import string
import random
import os
import re
file = open('file.dat', 'r')
file=file.read().split(',')
print file
def id_generator(size=28, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
if os.path.exists('newfile.txt'):
os.remove('newfile.txt')
else:
file = open("newfile.txt", "w")
file.write(id_generator())
file.close()
if re.search(r"THIS IS A STRING", file):
print("success!")
I'm trying to achieve this with re
module, since it should read character by character, finding it's position in the random generated string.
Not just comparing but also finding the position of the matching characters (if any)
The file.dat
file contains the THIS IS A STRING
string, which I call the 'static' one, it doesn't changes, it should be matched by the random generated ones process .
The newfile.txt
prints the random generated string.
So, in a nutshell, how can I read the string on file.dat
character by character, and same goes for the random generated string on newfile.txt
?
I hope I've explained myself.
Answer
At the least, you should probably change this
file=file.read().split(',')
print file
and this
if re.search(r"THIS IS A STRING", file):
print("success!")
to this
data=file.read().split(',')
print data
and this
if re.search(r"THIS IS A STRING", data):
print("success!")
You are losing the file contents when you open the output file:
else:
file = open("newfile.txt", "w")
No comments:
Post a Comment