Programming Examples

Python program to write first n prime number in text file


Write a Python program which write a first n prime in txt file (each line contain one prime no.)

Solution:

prime=[]
limit=int(input("How many prime numnbers you want to write : "))
n=2
count=0
while count<=limit:
    flag=True
    for a in range(2,n):
        if n%a==0:
            flag=False
    if flag==True:
        count=count+1
        prime.append(str(n)+"\n")
    n=n+1
fp=open("prime.txt","w")
fp.writelines(prime)
fp.close()
Output

Online Exam Quiz for One day Exam Online Typing Test CCC Online Test 2026 Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level Online Test in Hindi Best Website and Software Company in Allahabad