简体   繁体   中英

Python script to read from a file and get values

If in a file the values present are in either " or , separated values

         "Name" "Tom" "CODE 041" "Has"
         "Address" "NSYSTEMS c/o" "First Term" "123" 18  
         "Occ" "Engineer" "Level1" "JT" 18

How should the python script be written so as to get all the above values individually

Your question is a little vague, and there are no commas in your example, so it's a bit hard to provide a good answer.

On your example file containing

"Name" "Tom" "CODE 041" "Has"
"Address" "NSYSTEMS c/o" "First Term" "123" 18  
"Occ" "Engineer" "Level1" "JT" 18

this script

import csv
reader = csv.reader(open('test.txt'), delimiter=' ', quotechar='"')
for row in reader:
    print(row)

produces

['Name', 'Tom', 'CODE 041', 'Has']
['Address', 'NSYSTEMS c/o', 'First Term', '123', '18']
['Occ', 'Engineer', 'Level1', 'JT', '18']

This assumes that the delimiter between values is a space. If it's a tab, use delimiter='\\t' instead.

You're out of luck with this approach if delimiters change throughout the file - in this case they are not valid CSV/TSV files anymore. But all this is just speculation until you can provide some actual and relevant examples of the data you want to analyse.

An alternative approach to using the csv reader.

in.txt

"Name" "Tom" "CODE 041" "Has"
"Address" "NSYSTEMS c/o" "First Term" "123" 18  
"Occ" "Engineer" "Level1" "JT" 18

parse.py

for i in [line.split('"') for line in open("in.txt")]: # split on the separator
    for j in i: # for each token in the split string
        if len(j.strip())>0: # ignore empty string, like the spaces between elements
            print j.strip()

out.txt

Name
Tom
CODE 041
Has
Address
NSYSTEMS c/o
First Term
123
18
Occ
Engineer
Level1
JT
18

But I would call your values " enclosed . And I cant see any , separated . Could you expand your test data? Show some rows with , separated values and Ill expand my code.

Use csv module it will handle all type of delimiters and quotes properly, writing such code using split etc isn't trivial

import csv
import StringIO

data = '''"Name" "Tom" "CODE 041" "Has"
"Address" "NSYSTEMS c/o" "First Term" "123" 18  
"Occ" "Engineer" "Level1" "JT" 18"
'''

reader = csv.reader(StringIO.StringIO(data), delimiter=' ')
for row in reader:
    print row

Output:

['Name', 'Tom', 'CODE 041', 'Has']
['Address', 'NSYSTEMS c/o', 'First Term', '123', '18']
['Occ', 'Engineer', 'Level1', 'JT', '18']

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