[英]How do I read data from a file using Python?
I am looking for a lookup function for print corresponding names.我正在寻找查找 function 以打印相应的名称。 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 name我的脚本中有一个变量“用户”我想检查第一列中的变量,如果值匹配则打印相应的名称
Eg if “user”==a then print “Chief manager”
例如,如果“user”==a 则打印“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.如果要解析 CSV 文件,则取决于文件的实际格式。 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.