(Note: I'm note quite sure whether you want to keep the +
sign. The following codes assume you do. Otherwise it's easy to get rid of the +
with a bit of string manipulations).
Input file
Here is the input file...
dat1.txt
:
Code-6667+
Name of xyz company+
Address +
Number+
Contact person+
Code-6668+
Name of abc company,Address, number, contact person+
Code-6669+
name of company , Address+
number , contact person +
Code
Here is the code... (comment / uncomment the print
block for Python 2.x/3.x version)
mycode.py
:
import sys
print sys.version
# open input text file
f = open("dat1.txt", "r")
# initialise our final output - a phone book
phone_book = {}
# parse text file data to phone book, in a specific format
code = ''
for line in f:
if line[:5] == 'Code-':
code = (line[:4] + line[5:]).strip()
phone_book[code] = []
elif code:
phone_book[code].append(line.strip())
else:
continue
# close text file
f.close()
# print result to console (for ease of debugging). Comment this block if you want:
for key, value in phone_book.items():
#python 3.x
# print("{0} - Company details: {1}".format(key, value))
#python 2.x
print key + " - Company details: " + "".join(value)
# write phone_book to dat2.txt
f2 = open("dat2.txt", "w")
for key, value in phone_book.items():
f2.write("{0} - Company details: {1}\n".format(key, value))
f2.close()
Output
Here is what you will see in console (via print()
) or dat2.txt
(via f2.write()
)...
# Code6667+ - Company details: ['Name of xyz company+', 'Address +', 'Number+', 'Contact person+']
# Code6668+ - Company details: ['Name of abc company,Address, number, contact person+']
# Code6669+ - Company details: ['name of company , Address+', 'number , contact person +']
Screenshot
