Search code examples
pythonrandomlines

Python - Open TXT, Randomize, Save as New File


I've been messing around with randomizing in python for awhile now but for some reason I'm stuck here. Maybe it's just too late at night...

Anyway, I'm looking for a quick an easy method in Python to;

  • Open TXT File
  • Randomize Lines
  • Save as new TXT File

I'm feeling kinda dumb here... Any help is appreciated! Thanks!


Solution

  • Use random.shuffle to randomize a sequence:

    import random
    
    with open('filename', 'rb') as infile:
        lines = infile.readlines()
    
    random.shuffle(lines)
    
    with open('newfilename', 'wb') as outfile:
        outfile.writelines(lines)
    

    Edit: The method of shuffling suggested in the other answer is wrong. See the comments and the links therein. Here is a more correct example of a shuffle:

    end = len(lines) - 1
    for i in range(end + 1):
        choice = random.randint(i, end)
        lines[i], lines[choice] = lines[choice], lines[i]
    

    After this shuffle, assuming perfect randomness from randint, the position of a line is completely uncorrelated with its position before the shuffle. Using the naive algorithm in the other answer, that isn't the case. The two shuffles both take the same number of operations.