One of your issues is you are attempting to read from a file which is opened for writing. This is not possible. You need to read from one file, and write to another. The below code uses the with
-statement to open the input file and an output file.
You don't need regular expressions here. You can simply check if the line ends with either dev
or supp
and append the text you want accordingly. For that, use the str.endswith()
:
with open("text.txt", "r") as inp, open("out.txt", "w") as output:
for line in inp:
l = line.strip()
if l.endswith("dev"):
output.write("{} <- He's a developer\n".format(l))
if l.endswith("supp"):
output.write("{} <- He's a support guy\n".format(l))
Your python version is six years old. You should consider updating to at least python 2.7.x but preferrably to python 3.x. The with
-statement is not available in python 2.4. You have to open and close the files manually:
inp = open("text.txt", "r")
output = open("out.txt", "w")
for line in inp:
l = line.strip()
if l.endswith("dev"):
output.write("%s <- He's a developer\n" % l)
if l.endswith("supp"):
output.write("%s <- He's a support guy\n" % l)
inp.close()
output.close()
Outputs to out.txt:
msvalkon@Lunkwill:/tmp$ cat out.txt
1. Luv_dev <- He's a developer
2. Amit_dev <- He's a developer
3. Sandeep_supp <- He's a support guy
4. Prateek_supp <- He's a support guy
5. Sumit_dev <- He's a developer
6. Shashank_dev <- He's a developer
7. Kush_supp <- He's a support guy
8. Ritesh_dev <- He's a developer
9. Shubham_supp <- He's a support guy
10. Ravi_dev <- He's a developer
msvalkon@Lunkwill:/tmp$