splitting a file randomly in python
Question: I have a input file word.txt.I am trying to splitting the file in 75%-25%
randomly in python.

    
    
    def shuffle_split(infilename, outfilename1, outfilename2):
        from random import shuffle
    
        with open(infilename, 'r') as f:
            lines = f.readlines()
    
        # append a newline in case the last line didn't end with one
        lines[-1] = lines[-1].rstrip('\n') + '\n'
        traingdata = len(lines)* 75 // 100
        testdata = len(lines)-traingdata
        with open(outfilename1, 'w') as f:
            f.writelines(lines[:traingdata])
        with open(outfilename2, 'w') as f:
            f.writelines(lines[:testdata])
    

But this code is writing the first 75% of the original file in the first
output file and again the same 25% of the original file in the second output
file.Could you please suggest me some way to solve it.


Answer: The problem is that in this line

    
    
     f.writelines(lines[:testdata])
    

you are saying "everything from index 0 to index testdata":

    
    
     f.writelines(lines[0:testdata])
    

which is not what you want. Just change it to

    
    
     f.writelines(lines[testdata:])
    

which means "everything from (testdata) to the end of the list". That should
work. Or even simpler

    
    
     f.writelines(lines[traingdata + 1:])
    

This line says "everything from (traindata + 1) to the end of the list".

