Techgeeks1
Techgeeks1

Reputation: 596

How to get data of that line and before that line and after that line in python

I have a file example.txt which contains the following data in it 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

I want to store data in three diffrent files.If name is abc email,name and country should be stored in abc.txt file.If name is xyz all the data of xyz should be placed in xyz.txt. This is my code It is only saving data for name line.But i want email and country also.

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)            

Upvotes: 1

Views: 98

Answers (2)

Vasilis G.
Vasilis G.

Reputation: 7844

This should do the trick:

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")

Upvotes: 3

Jan Zeiseweis
Jan Zeiseweis

Reputation: 3738

Probably not the most elegant solution but it works:

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')

Upvotes: 1

Related Questions