Writing content into a file in python

Preview




Writing content into a file in python

Different predefined functions of C language for writing content into file are:

There are two  predefined functions provided by Python to write data into a data file

1. write()

write() function is used to write content into a data file.The syntax of write() function is:

<fileobject>.write(str)

Here fileobject is the object that is linked to a data file in which we want to write some content.

str refers to string variable of constant whose value we want to write into data file.

**Before using write() function, file must be opened in write mode or append mode.

Example 1

file1=open("data.txt","w")
file1.write("This is a file")
file1.close()

#Above code will create a new file data.txt and write “This is a file” into the file.

Example 2

file2=open("data1.txt","w")
file2.write("This is line 1")
file2.write("\nThis is line 2")
file2.write("\nThis is line 3")
file2.close()

#Above code will create a new file data2.txt and write following three lines int the file.
This is line 1
This is line 2
This is line 3
into the file.

Example 3

file3=open("data3.txt","w")
print("Enter three names")
for i in range(3):
     name=input('Enter name')
     file3.write(name + '\n' )
file3.close()

Output

Enter three names
Enter nameaman
Enter namesuman
Enter nameraman

#Above code will create a new file data3.txt and write following three names into the file.
aman, suman and raman

2. writelines()

writelines() function is also used to write content into a data file.The syntax of writelines() function is:

<fileobject>.writelines(List)

Here fileobject is the object that is linked to a data file in which we want to write some content.

List refers to a List whose values we want to write into data file.

**Before using writelines() function, file must be opened in write mode or append mode.

Example 1

file5=open("data5.txt","w")
L1=['amit','sumit','vijay']
file5.writelines(L1)
file5.close()

#Above code will create a new file data5.txt and write three values contained in list i.e. ‘amit’, ‘sumit’ ,’vijay into the file.

Example 2

file6=open("data6.txt","w")
L1=[]
print("Enter three names")
for i in range(3):
     name=input('Enter name')
     L1.append(name+"\n")
file6.writelines(L1)
file6.close()

Output

Enter three names
Enter nameaman
Enter namesuman
Enter nameraman

# Above code allow you to enter three names and append entered values into llist named L1 and insert values contained in list L1 i.e. aman, suman and raman into file data6.txt.

Appending data into a File

When we open a file in “w” (write mode), Python creates a new file. If file already exists, it will overwrite the file with new contents. 

If we want to write data into the file while retaining the old data, then we can open the file in append mode by using “a”, ,”w+”  or “r+” .




Lesson tags: write() function in python, writeline() function in python
Back to: Python Programming Tutorial