Home »
Python »
Python Programs
Python program to write data to a file
Python | Write data to a file: In this tutorial, we will learn about writing to a file and write a Python program to write data to a file entered by the user.
By Shivang Yadav Last updated : July 05, 2023
Write operation on a file
Write operation is the process of writing data to file by the program. This is done using the write() method available in the Python library.
The Python program is opened in 'w' mode, to write files.
How to write data to a file?
The following are the steps to write data to a file in Python:
- Step 1: Open the file using w mode. (if the file is not present the write mode will create a new one).
- Step 2: Get input from the user.
- Step 3: User the write() method to write the contents to the file.
- Step 4: Close the file.
Python program to write data to a file
F=open("drinks.dat","w")
while(True):
v=input("Enter Drink Name : ")
if(v==""):
break
F.write(v+"\n")
F.close()
Output
Enter Drink Name : RedBull
Enter Drink Name : Cafe Mocha
Enter Drink Name : Americano
Enter Drink Name : Coca Cola
Enter Drink Name : Tea
Enter Drink Name :
File : drinks.dat
RedBull
Cafe Mocha
Americano
Coca Cola
Tea
Python file handling programs »