Home > Back-end >  Parsing a TXT file in Python
Parsing a TXT file in Python

Time:03-31

At the bottom is the way I usually parse a TXT file (works fine!)

My question: is there a more elegant/pythonic/best-practice way to get

[line.strip()

for line in file.readlines()

if line.strip()]

### create a sample TXT file for demo

with open('recipe.txt', 'w') as file:
   file.write("""
  3 oeufs
180 g de sucre
  
 le zest de 2 citrons

""")

### parse the sample TXT file

with open('recipe.txt', 'r') as file:
   lines = [line.strip() 
      for line in file.readlines() 
      if line.strip()]

# ['3 oeufs', '180 g de sucre', 'le zest de 2 citrons']

CodePudding user response:

You can use the walrus operator (assignment expressions) in python 3.8 to save the strip to a variable and then use that

[x for line in file.readlines() if (x := line.strip())]

CodePudding user response:

I don't know if this is considered "more Pythonic" but is the way I usually do it:

with open('recipe.txt') as infile:
    lines = [m for m in map(str.strip, infile) if m]

CodePudding user response:

As a best practice, I recommend to divide the access to the file system and the parsing.

Benefit: You can test your parsing script and the access to the data separately.

    ### parse the sample TXT file

def read_file(file_name):
    with open(file_name, 'r') as file:
        lines = list(file)
    return lines


def parse_lines(lines):
    stripped_lines = [line.strip() for line in lines]
    output = [line for line in stripped_lines if line]
    return output
    # ['3 oeufs', '180 g de sucre', 'le zest de 2 citrons']
  • Related