开发者

related to list and file handling?

I have file with conte开发者_如何学JAVAnts in list form such as

[1,'ab','fgf','ssd']
[2,'eb','ghf','hhsd']
[3,'ag','rtf','ssfdd']

I want to read that file line by line using f.readline and assign each line to a list.

I tried doing this:

k=[ ]
k=f.readline()
print k[1] 

I expected a result to show 2nd element in the list in first line, but it showed the first bit and gave o/p as '1'.

How to get the expected output?


If all you want is to take the input format shown and store it as a list attempting to execute the input file (with eval()) is not a good idea. This leaves your program open to all sorts of accidentally and intentionally harmful input. You are better advised to just parse the input file:

s=f.readline()[1:-1]
k = s.split(',')
print k[1]


readline just returns strings. You need to cast it to what you want. eval does the job, be warned that however it does execute everything inside the string, so this is only an option if you trust the input (i.e. you've saved it yourself).

If you need to save data from your program to a file, you might want to use pickle.


if the sample posted is actual content of your file (which I highly doubt), here is what you could do starting with Python 2.6, docs:

>>> for line in open(fname):
    print(ast.literal_eval(line)[1])


ab
eb
ag


You could use eval on each line; this would evaluate the the expression in the line and should yield your expected list, if the formatting is correct.

A safer solution would be a simple CSV parser. For that your input could look something like this (comma-separated):

123,321,12,123,321,'asd',ewr,'afdg','et al',213

Maybe this is feasible.


Maybe You can use eval as suggested, but I'm just curious: Is there any reason not to use JSON as file format?


You can use the json module:

import json

with open('lists.txt', 'r') as f:
  lines = f.readlines()
  for line in lines:
    line = line.replace("'", '"')
    l = json.loads(line)
    print l[1]

Outputs:

ab
eb
ag
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜