NeoVe NeoVe - 1 month ago 17
Python Question

Random string generation I/O python

I'm creating a python script which should create a new file every time it generates a new string (everytime the script is executed it prints out the string to file), and also compares this random string with a string which is a text like:

THIS IS A STRING
, which is located on another already created file.

For example, the string
THIS IS A STRING
is located on file called
file.dat
, and the random generated string should be written to a file, in this case I call it
newfile.txt
.

However, I have this code:

import string
import random

file = open('file.dat', 'r')
file=file.read()
print file

def id_generator(size=28, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
file = open("newfile.txt", "w")
file.write(id_generator())
file.close()


This code, simply reads the
file.dat
archive, prints it to console, then generates a random string and stores it on a file called
newfile.txt
, but it doesn't compares anything, so, to accomplish that I've modified the code like this:

import string
import random

file = open('bullshit.dat', 'r')
file=file.read()
print file

def id_generator(size=28, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
with open("newfile.txt", "r") as f: stored = f.readline()
if stored == id_generator():
print('success!')


Now, my problem is, that this code just reads an already created file, which is
newfile.txt
, I need to create a new one like the code I had before, but comparing the strings.

I tried modifying the last three lines like this:

with open("newfile.txt", "w") as f: stored = f.readline()
if stored == id_generator():
print('success!')


But it throws me:

Traceback (most recent call last):
File "string2.py", line 20, in <module>
with open("newfile.txt", "w") as f: stored = f.readline()
IOError: File not open for reading


How can I accomplish something like the first version, but comparing the strings as the second one?

Answer

Solution you had "w" which can only write to the file so you have to open it as "r" which reads it.

import string
import random

file = open('test.dat', 'r')
file=file.read()
print file

def id_generator(size=28, chars=string.ascii_uppercase + string.digits):
    return ''.join(random.choice(chars) for _ in range(size))
with open("newfile.txt", "r") as f: stored = f.readline()
if stored == id_generator():
    print('success!')
Comments