Home »
Python »
Python programs
Python program to write data to file
Here, we are going to learn about writing to a file and writing a Python program to write data to a file entered by the user.
Submitted by Shivang Yadav, on February 21, 2021
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.
Algorithm to Write to 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 »
TOP Interview Coding Problems/Challenges