1

I'm reading in a text file and I am trying to erase everything except the first word on each line. So, what I am doing after reading the text file is splitting it with space as the delimetre and then storing the words in an array.

Now, my plan with the array is to save the first word, what is at location 0 as a new line in a text file. Then I will have a text file with only the first words of my original file.

What I am having trouble with is writing the array[0] to a new line in a new text file and then saving that text file. How can I do that in Python 2.7 ?

Here is my code so far. The part that I don't know how to do is the part that is just a comment.

import sys
import re

read_file = open(sys.argv[1]) #reads a file

for i in iter(read_file): #reads through all the lines one by one

    k = i.split(' ') #splits it by space

    #save k[0] as new line in a .txt file

#save newly made text file
#close file operations

read_file.close()
1
  • read_file will be an iterable so no need for iter(). Commented Jun 4, 2013 at 2:03

1 Answer 1

4

Use the with statement for handling files, as it automatically closes the file for you.

Instead of using file.read you should loop over the file iterator itself as it returns one line at a time and is going to be more memory efficient.

import sys
with open(sys.argv[1]) as f, open('out.txt', 'w') as out:
    for line in f:
       if line.strip():                     #checks if line is not empty
           out.write(line.split()[0]+'\n')
Sign up to request clarification or add additional context in comments.

4 Comments

When I run python edit.py file.txt and edit.py has only your code in it, I get an empty text file and this is printed in the terminal: File "edit.py", line 4, in <module> out.write(line.split[0]+'\n') TypeError: 'builtin_function_or_method' object is not subscriptable
@JayGatz fixed the typo, line.split()[0]
Now there is an IndexError: list index out of range. With an empty text file being written.
@JayGatz that means your text file contains some empty lines.

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.