简体   繁体   中英

Fetching *list* contents from a text file in Python

I need help to fetch list back from a file where each line is stored as a list. For example, check the following lists.txt file

["1","Andy Allen","Administrator"]
["2","Bob Benny","Moderator"]
["3","Zed Zen","Member"]

I need the content to be accessible and be displayed in the following manner

SN : 1
Name : Andy Allen
Position : Administrator

SN : 2
Name : Bob Benny
Position : Moderator

SN : 3
Name : Zed Zen
Position : Member

PS : I know I could have saved it with Delimiters and access list elements with split function... But it seems that when using a particular delimiter as the text content causes the function to function abnormally..

This format, using only double quotes and not single, looks like JSON (JavaScript object notation) . Fortunately, the json module that comes with Python 2.6 or later can parse JSON. So read each line, parse it as JSON (using json.loads ), and then print it out. Try something like this:

import json
with open("lists.txt", "r") as infp:
    rows = [json.loads(line) for line in infp]
for sn, name, position in rows:
    print("SN : %s\nName : %s\nPosition : %s\n" % (sn, name, position))

Taming CSV

Another solution is to export in tab- or comma-separated values formats and use Python's csv module to read them. If (for example) a value in a comma-separated file contains a comma, surround it with double quotes ( " ):

2,Bob Benny,"Moderator, Graphic Designer"

And if a value contains double quote characters, double them and surround the whole thing with double quotes. For example, the last element of the following row has the value "Fossils" Editor :

5,Chester from Tilwick,"""Fossils"" Editor"

A spreadsheet app, such as Excel, LibreOffice Calc, or Gnumeric, will do this escaping for you when saving in separated format. Thus lists.csv would look like this:

1,Andy Allen,Administrator
2,Bob Benny,"Moderator, Graphic Designer"
3,Zed Zen,Member
5,Chester from Tilwick,"""Fossils"" Editor"

Which can be parsed similarly:

import csv
with open("lists.csv", "r", newline="") as infp:
    # use "excel" for comma-separated or "excel-tab" for tab-separated
    reader = csv.reader(infp, "excel")
    rows = list(reader)
for sn, name, position in rows:
    print("SN : %s\nName : %s\nPosition : %s\n" % (sn, name, position))

(This is for Python 3. Python 2's csv module differs slightly in that open should be binary: open("lists.txt", "rb") .)

如何使用grep抓取[]中的所有内容?

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