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 »





Comments and Discussions




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.