info-farmer
info-farmer

Reputation: 265

How to give serial numbers before my output strings?

I have written a python script to get the name of Wikimedia contributors in a CSV output file as follows;-

velu

ramu

ஆதி

How can i give serial numbers to those names? Like below;-

1.velu

2.ramu

3.ஆதி

My code: It reads a file and removes duplicates. Finally, i want to give serial numbers.

content = open('contributors.csv','r').readlines()
content4set = set(content)
cleanedcontent = open('contributors-cleaned.csv','w')
for line in content4set:
    cleanedcontent.write(line.replace('பக்கம்','அட்டவணை_பேச்சு'))
    line=line.strip()
    print(line)

Upvotes: 1

Views: 1111

Answers (3)

info-farmer
info-farmer

Reputation: 265

I learned from both your approaches and rearranged with another article as follows;-

content = open('contributors.csv','r').readlines()
content4set = set(content)
cleanedcontent = open('contributors-cleaned.csv','w')
for i, line in enumerate(content4set,1):
    cleanedcontent.write("{}.{}".format(str(i+1),line.replace('பக்கம்','அட்டவணை_பேச்சு')))
    line=line.strip()
    print(i, line)

My output result is,

1 velu

2 ramu

3 ஆதி

Thanks indeed both of you.

Upvotes: 0

Ramchandra Apte
Ramchandra Apte

Reputation: 4079

Use enumerate to get the index along with each line. i is the index of the line. Note that you'll need Python 3.6 or newer as this code uses formatted strings.

content = open('contributors.csv','r').readlines()
content4set = set(content)
cleanedcontent = open('contributors-cleaned.csv','w')
for i, line in enumerate(content4set):
    line = line.strip().replace('பக்கம்','அட்டவணை_பேச்சு')
    line = f"{i+1}. {line}"
    print(line, file = cleanedcontent)
    print(line)

Upvotes: 0

Tzomas
Tzomas

Reputation: 704

yes, you can.

content = open('contributors.csv','r').readlines()
content4set = set(content)
cleanedcontent = open('contributors-cleaned.csv','w')
for i, line in enumerate(content4set):
    cleanedcontent.write("{}.{}".format(str(i+1),line.replace('பக்கம்','அட்டவணை_பேச்சு')))
    line=line.strip()
    print(line)

Upvotes: 1

Related Questions