Last modified: Jun 02, 2023 By Alexander Williams

Read File and Split The Result in Python

In this tutorial, we're going to learn two things:

  • Read a file and split the output.
  • Read a file and split line by line.

Read a file and split the output

Before writing our program, let's see the file that we'll read and split.

file.txt

Now let's write our program that reads file.txt and splits the output.


with open('file.txt', 'r') as f:
    txt = f.read()
    sp = txt.split()
    print(sp)

output

['Python', 'is', 'an', 'interpreted,', 'high-level', 'and', 'general-purpose', 'programming', 'language.', "Python's", 'design', 'philosophy', 'emphasizes', 'code', 'readability', 'with', 'its', 'notable', 'use', 'of', 'significant', 'whitespace.', '']

Let me explain the code above:

  • 1. open the file.txt and read it.
  • 2. split the file output.
  • 3. print the result.

Read the file and split lines

In this next part of the tutorial, we'll read file.txt and split it line by line.


with open('file.txt', 'r') as f:
    for l in f:
        sp = l.split()
        print(sp)

output

['Python', 'is', 'an', 'interpreted,', 'high-level', 'and', 'general-purpose', 'programming', 'language.']
["Python's", 'design', 'philosophy', 'emphasizes', 'code', 'readability', 'with', 'its', 'notable', 'use', 'of', 'significant', 'whitespace.s']

Let me explain what we did:

  • 1. open the file.
  • 2. read each line by using for loop.
  • 3. split the line using the split() method.
  • 4. print result.