0

I have a file that looks something like this:

o 345644 0 0 0 1
0 454545 0 0 2 2
0 423233 0 0 1 1
. .      . . . .
. .      . . . .
. .      . . . .

What I would like to do is extract column two and column 6 to create a text file. I wrote the following code but the output file I am getting only contains the second column. The desired output I am would like is a new file that looks like this:

newfile.txt

 345644 1
 454545 2
 423233 1
 .      .
 .      .
 .      .

Here is my code :

dta_2path = open("file.txt","r")
ws_2= open("newfile.txt", "w")

for line in dta_2path:
    if line.strip():
       ws_2.write("\t".join(line.split()[1:2]+ line.split()[9:10])+"\n") 

dta_2path.close()
ws_2.close()

Any help in how to fix this would be appreciated. Thanks in advance!

2
  • Seems like 9:10 should be 5:6. But you're only extracting one column, so why not use line.split()[1] and lines.split()[5] ? Commented May 5, 2016 at 17:20
  • I used line.split()[1] and line.split()[5] but I get a syntax error in dta_2path.close(). Not sure why. Commented May 5, 2016 at 17:33

2 Answers 2

2

Try this:

for line in dta_2path:
    if line.strip():
        cols = line.split()
        ws_2.write(cols[1] + "\t" + cols[5] + "\n")
Sign up to request clarification or add additional context in comments.

3 Comments

I get the following error: ws_2.write(cols[1], "\t", cols[5], "\n") TypeError: function takes exactly 1 argument (4 given)
Grrr! You're right, have to use concatenation. I've edited it with '+' instead of ','
Thanks! That makes sense now.
0

You are taking the wrong indices. It should work if you use line.split(" ")[1] and line.split(" ")[5].

1 Comment

I was adding the indices [1:2] and [9:10] because I was counting the spaces too. I changed to what you said but it didn't work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.