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")
.)