Jump to content

Shuffle lines of a file using Python

IgorM

I am trying to shuffle the lines of a file to use on a perceptron algorithm but the problem is by doing so one line always has 2 entries:

 

import random
with open("infile.txt") as f:
    lines = f.readlines()
random.shuffle(lines)
with open("outfile.txt", "w") as f:
    f.writelines(lines)

Original part of the source file:

5.1,3.5,1.4,0.2,Iris-setosa
4.9,3.0,1.4,0.2,Iris-setosa
4.7,3.2,1.3,0.2,Iris-setosa
4.6,3.1,1.5,0.2,Iris-setosa
5.1,3.3,1.7,0.5,Iris-setosa
4.8,3.4,1.9,0.2,Iris-setosa
5.0,3.0,1.6,0.2,Iris-setosa
5.0,3.4,1.6,0.4,Iris-setosa
5.2,3.5,1.5,0.2,Iris-setosa

Output file:

 

5.0,3.5,1.6,0.6,Iris-setosa
6.4,2.7,5.3,1.9,Iris-virginica
6.6,2.9,4.6,1.3,Iris-versicolor
6.3,2.3,4.4,1.3,Iris-versicolor
5.9,3.0,5.1,1.8,Iris-virginica4.6,3.1,1.5,0.2,Iris-setosa
5.0,3.3,1.4,0.2,Iris-setosa
5.7,2.8,4.1,1.3,Iris-versicolor
5.1,3.5,1.4,0.2,Iris-setosa
5.8,4.0,1.2,0.2,Iris-setosa
6.0,2.2,4.0,1.0,Iris-versicolor
4.9,3.1,1.5,0.1,Iris-setosa
6.3,2.5,5.0,1.9,Iris-virginica
5.1,3.4,1.5,0.2,Iris-setosa
4.9,3.0,1.4,0.2,Iris-setosa

 

Link to comment
Share on other sites

Link to post
Share on other sites

11 minutes ago, IgorM said:

I am trying to shuffle the lines of a file to use on a perceptron algorithm but the problem is by doing so one line always has 2 entries

Just a hunch, but does the last line in the input-file include the newline-character or not? I'd assume it doesn't, which would explain your issue. You could simply check if the last line has a newline-character in it and, if it doesn't, add it there.

Hand, n. A singular instrument worn at the end of the human arm and commonly thrust into somebody’s pocket.

Link to comment
Share on other sites

Link to post
Share on other sites

8 hours ago, WereCatf said:

Just a hunch, but does the last line in the input-file include the newline-character or not? I'd assume it doesn't, which would explain your issue. You could simply check if the last line has a newline-character in it and, if it doesn't, add it there.

that was it. Thanks!

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×