读取以特定字母开头的行的循环

时间:2013-08-07 09:31:07

标签: python loops dictionary readline

我正在使用for循环来读取文件,但我只想读取特定行,例如以“af”和“apn”开头的行。是否有任何内置功能来实现这一目标?

阅读后如何分割这条线? 如何将拆分中的元素存储到字典中? 让我们说分裂后的第一个元素是员工ID我将它存储在字典中然后第二个元素是他的全名我想将它存储在字典中。
所以,当我使用这行“employee_dict {employee_ID}”时,我会得到他的全名吗?

谢谢。

4 个答案:

答案 0 :(得分:0)

你可以很容易地这样做

f = open('file.txt', 'r')

employee_dict = {}

for line in f:
    if line.startswith("af") or line.startswith("apn"):
        emprecords = line.split() #assuming the default separator is a space character
        #assuming that all your records follow a common format, you can then create an employee dict
    employee = {}
     #the first element after the split is employee id
    employee_id = int(emprecords[0])
    #enter name-value pairs within the employee object - for e.g. let's say the second element after the split is the emp name, the third the age
   employee['name'] = emprecords[1]
   employee['age'] = emprecords[2]
   #store this in the global employee_dict
   employee_dict[employee_id] =  employee

在完成上述操作后,要检索员工ID 1的名称:

print employee_dict[1]['name']

希望这可以让您了解如何进行

答案 1 :(得分:0)

如果您的文件看起来像

af, 1, John
ggg, 2, Dave

你可以创建像

这样的字典
d = {z[1].strip() : z[2].strip() for z in [y for y in [x.split(',') for x in open(r"C:\Temp\test1.txt")] if y[0] in ('af', 'apn')]}

更易阅读的版本

d = {}
for l in open(r"C:\Temp\test1.txt"):
    x = l.split(',')
    if x[0] not in ('af', 'apn'): continue
    d[x[1].strip()] = x[2].strip()

这两个解决方案都会在此示例中为您提供d = {'1': 'John'}。要从字典中获取名称,您可以执行name = d['1']

答案 2 :(得分:0)

prefixes = ("af", "apn")
with open('file.txt', 'r') as f:
    employee_dict = dict((line.split()[:2]) for line in f if any(line.startswith(p) for p in prefixes))

答案 3 :(得分:0)

dictOfNames={}
file = open("filename","r")
for line in file:
if line.startswith('af') or if line.startswith('apn'):
    line=line.split(',') #split using delimiter of ','
    dictOfNames[line[1]] = line[2] # take 2nd element of line as id and 3rd as name

如果以'af'或'apn'开头,上面的程序将读取文件并将第二个元素存储为id,将第三个元素存储为名称。假设逗号是分隔符。

现在您可以使用dictOfNames [id]来获取名称。