简体   繁体   中英

Parsing a TXT file in Python

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']

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())]

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]

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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM