如何在python中获取该行以及该行之前和该行之后的数据

时间:2017-12-21 11:15:15

标签: python file

我有一个文件example.txt,其中包含以下数据 的 example.txt文件:

Email & Password: hifza
name: abc
Country: US


Email & Password: trfff
name: abc
Country: US

Email & Password: trfff
name: xyz
Country: US

Email & Password: trfff
name: ttt
Country: US

我想将数据存储在三个不同的文件中。如果名称是abc电子邮件,名称和国家/地区应存储在abc.txt文件中。如果名称为xyz,则xyz的所有数据都应放在xyz.txt中。 这是我的代码它只保存名称行的数据。但我也想要电子邮件和国家。​​

with open("example.txt") as f:
   with open("abc.txt", "w") as f1:
      for line in f:
        if "abc" in line:
            f1.write(line) 
        elif "xyz" in line:
            with open("xyz.txt", "w") as f2:
                f2.write(line)  
        elif "ttt" in line:
            with open("ttt.txt", "w") as f3:
                f3.write(line)            

2 个答案:

答案 0 :(得分:3)

这应该可以解决问题:

with open("test.txt", "r") as infile:

    line = infile.read().split("\n\n")
    for l in line:
        l = l.strip() // get rid spaces and empty lines
        l = l.split("\n")
        filename = l[1].split(":")[1].strip() + ".txt"
        with open(filename, "w+") as outfile:
            for i in l:
                outfile.write(i + "\n")

答案 1 :(得分:1)

可能不是最优雅的解决方案,但它有效:

with open('fil') as f_in:
    with open('abc.txt', 'w') as abc, \
            open('xyz.txt', 'w') as xyz, \
            open('ttt.txt', 'w') as ttt:
        lines = f_in.read().split('\n\n')

        for line in lines:
            if 'name: abc' in line: out = abc
            elif 'name: xyz' in line: out = xyz
            elif 'name: ttt' in line: out = ttt
            else: out = None
            if out:
                out.write(line.strip() + '\n')