开发者

How do I read data from a file using Python?

I am looking for a lookup function for print corresponding names. I have a list file

a Chief manager
b Assistant general manager
c general manager
D CTO
E CEO

I have a variable “user” in my script I want to check the variable in first column, if the value match then print corresponding开发者_如何学JAVA name

Eg if “user”==a then print “Chief manager”


Using a dictionary will be easier.

d = { 'a': 'Chief Manager', 'b': 'Assistant General Manager', 'c': 'General Manager', 'D': 'CTO', 'E': 'CEO' }
user = 'a'
print(d[user])
# Chief Manager

To load that file into a dictionary, you could do this:

with open('/path/to/my/file') as myFile:
    d = dict(line.strip().split(None, 1) for line in myFile)

print(d['a'])
# Cheif manager

If you want to parse a CSV file, it depends on how the file is actually formatted. If it looked like this:

a,"Cheif manager"
b,"Assistant general manager"
c,"general manager"
D,"CTO"
E,"CEO"

You could read that in like this:

from csv import reader
d = dict(row for row in reader(open('/path/to/my/file'), delimiter=',', quotechar='"'))
print(d['a'])
# Cheif manager


Assuming that the first column would be unique in someway, your first task would be to construct a dictonary with keys from the first column and values from the second.

to construct the dictionary, try it in the following manner.

org_dict = dict()
line = 'a Chief manager'
key,value = line.split(None,1)
org_dict[key] = value

Now to get each line from your file, you can open the file and read then line by line.

with open('myfile') as f:
    for line in f:
        # process your line
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜