read file and separate line by whitespace in python

To read a file and separate each line by whitespace, you can use the following code:

main.py
with open('filename.txt', 'r') as file:
    for line in file:
        words = line.strip().split()
        # Use the words variable, which is a list containing each word on the line
182 chars
5 lines

Here's what each line of the code does:

  • with open('filename.txt', 'r') as file: opens the file named filename.txt in read mode and assigns it to the variable file. The with statement ensures that the file is automatically closed when the block of code is exited.
  • for line in file: loops over each line in the file object.
  • line.strip() removes any leading or trailing whitespace from the line.
  • line.strip().split() splits the line into a list of words, using whitespace as the delimiter. The resulting list is assigned to the words variable.

You can then use the words variable to access each word in the line, for example:

main.py
for line in file:
    words = line.strip().split()
    first_word = words[0]
    second_word = words[1]
    # do something with first_word and second_word
155 chars
6 lines

Note that if you want to read a file with a different delimiter (e.g. commas), you can pass that delimiter as an argument to the split() method, like this: line.strip().split(',').

gistlibby LogSnag