Program to take five names from users and enter into text file

In this program, we will be creating a text file. Asking user to enter five names and then writing those five names into a text file

Use open() function for reading or writing into a file. open() functions takes three arguments filename, mode and buffer. In the below line, we have submitted two parameters with open() function file name and mode.

file = open("C:/Users/rohit/Desktop/IPs.txt",'w')

Below are the three basic modes

r = Reading content from a file
w = Writing into a file. Previous data will be overwritten
a = Appending or adding new content at the file of the file

Since our program deals with adding new content into a file, we are using mode ‘w’

Create two variables count and i.

count = 5
i = 1

Now using while loop for taking five names from keyboard and adding into a file.

while count != 0:
name = input('Enter Name#%d: '%i)
file.write(name)
file.write('\n')
count=count-1
i=i+1

Closing the file

file.close()

Closing file is very essential. File kept in open mode may get corrupted or using unnecessary memory space

Output

Enter Name#1: Python
Enter Name#2: Java
Enter Name#3: PHP
Enter Name#4: Perl
Enter Name#5: C++

Below is the file content

Complete Code

file = open("C:/Users/rohit/Desktop/IPs.txt",'w')
count = 5
i = 1
while count != 0:
    name = input('Enter Name#%d: '%i)
    file.write(name)
    file.write('\n')
    count=count-1
    i=i+1
file.close()
Advertisement

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s