I am somehow able to write the below code(taking help from various sources):
langs=['C','Java','Cobol','Python']
f1=open('a.txt','r')
f2=open('abc.txt','w')
for i in range(len(langs)):
for line in f1:
f2.write(line.replace('Frst languag','{}'.format(langs[i])))
f1.close()
f2.close()
Don't know why the the for loop is not running till the end. Because everytime i open the txt only 'C' gets stored in the txt. I want the script to run and at the end of the script's execution the txt should have the last value of the list (here python)
1 Answer 1
After the first pass of your inner for loop, f1 is pointing to the end of the file. So the subsequent passes don't do anything.
The easiest fix is to move f1=open('a.txt','r') to just before for line in f1:. Then the file will be re-read for each of your languages. (Alternatively, you might be able to restructure your logic so that you can handle all of the languages at the same time in one pass of the file.)
'{}'.format(langs[i])adds nothing to justlangs[i]. You're taking a string, and saying to format it as a string and then place it into a string with nothing else. Also, instead of doingfor i in range(len(langs)):and then usinglangs[i], just dofor lang in langs:and uselang.