4
I’m working on a game that involves permutations, to create a list of words, in several separate files. Problems start to arise when I require words with more than 4 letters, as the corresponding file becomes too heavy. What I wanted is for every time a given file reached 499 999 (eg.) I opened another file with the same name but with an extension. For example 4 character words "wl4_1.txt
, wl4_2.txt
..." where the "wl4_2.txt
" is the continuation of "wl4_1.txt
", and the first line of this ("wl4_2.txt
") would be the 500,000 number line of the "wl4_1.txt
", that is, we would close the "wl4_1.txt
" and continue our list on "wl4_2.txt
".
This code below works beautifully, I just wanted to add this feature I explained. In this example are words of 3 letters and is already heavy (830 584 lines):
import itertools
import string
def main():
alphabet = string.letters + string.digits + string.punctuation
alphaLen = len(alphabet)
print alphabet
for i in range(3):
NumToPerm = i+1 #remove 0 from the permutations function
fileTest = open("word_lists/wl" +str(NumToPerm)+ ".txt", "w")
perm(fileTest, alphabet, NumToPerm)
def perm(fileTest, alphabet, NumToPerm):
for p in itertools.product(alphabet, repeat=NumToPerm):
word = str(p)
for char in word:
if char in " (),'":
word = word.replace(char,'')
fileTest.write(word+ '\n')
fileTest.close()
main()
Obgado, but something is going on, I am giving error related to the file. I edited the code on top, in the attempt and put what I realized you told me
– Miguel
@Miguel What mistake are you making? From your edition, I saw that only corrected part of the problems, several of them mentioned in the answer are still there (for example, you are returning
fileTest
of its function, but is not using the return, so when you try to write in the stream already closed it should accuse an error. This is what is happening?).– mgibsonbr
Yes it is. ("...fileTest.write(word+ n') Valueerror: I/O Operation on closed file"). How to implement the return in this case?
– Miguel