Reputation: 55
Please have a look to the below output :-
Software_Engineer:
Networking
Software_Engineering
Computer_Graphics
Development
Design
Mechanical_Engineer:
Automata
(There is a new line character here)
I want output should be as :-
Software_Engineer: Networking Software_Engineering Computer_Graphics Development Design
Mechanical_Engineer: Automata
I wrote below code in python as of now :-
with open("split_module.txt") as f:
all_lines = f.readlines()
keys_col1 = []
values_col2 = []
for ids, values in enumerate(all_lines):
if ":" in all_lines[ids] and all_lines[ids+1] != "\n":
keys_col1.append(values.strip())
for value in keys_col1:
print(value)
I am now getting output as :-
Software_Engineer:
Software_Engineer:
Mechanical_Engineer:
Here, Why "Software_Engineer:" is repeating two times and how can I able to get output as :-
Software_Engineer: Networking Software_Engineering Computer_Graphics Development Design
Mechanical_Engineer: Automata
Please suggest as I am new to Python.... Thanks..!!
Upvotes: 1
Views: 45
Reputation: 55
I got the desired output by :-
fle=open("C:\Python27\projects\infile.txt")
fle2=open("C:\Python27\projects\outfile.txt",'w')
lst=fle.readlines()
for i in lst:
i=i.strip()
if i.endswith(':'):
fle2.write("\n")
fle2.write(i)
else:
fle2.write(i)
fle2.write(" ")
fle.close()
fle2.close()
Thanks for help..
Upvotes: 0
Reputation: 565
Quick and dirty
def f1(txt):
buffer = ""
for ee in txt.splitlines():
if ee.endswith(':'):
if buffer:
yield buffer.strip()
buffer = ""
buffer += ee + " "
yield buffer.strip()
then you can for
for i in f1(txt):
print(i)
you would use the same idea to read the data from file i wrote is as if this was all in string
Upvotes: 0
Reputation: 1943
Try this code
fle=open("C:\Python27\projects\infile.txt")
fle2=open("C:\Python27\projects\outfile.txt",'w')
lst=fle.readlines()
for i in lst:
i=i.strip()
if i.endswith(':'):
fle2.write("\n")
fle2.write(i)
else:
fle2.write(i)
fle2.write(" ")
fle.close()
fle2.close()
COntent of outflie.txt
Software_Engineer:Networking Software_Engineering Computer_Graphics Development Design
Mechanical_Engineer:Automata
Upvotes: 1