Python Program to Write to a File
Beginner · File handling
Writing to a file saves text so it is still there after the program ends. Opening a file in "w" (write) mode creates it if it does not exist and empties it if it does. This program writes a few lines to a file, then reads the file back to show what was saved.
Program
Wrote 3 lines to student.txt File contents: Roll no: 14 Name: Riya Sharma Class: 12 A
How it works
open("student.txt", "w")opens the file for writing and creates it if needed; if it already exists, its old contents are erased first.f.write()writes exactly the string it is given, so"\n"is added to put each item on its own line.write()only accepts strings, so a number has to be turned into text withstr()before it is written.- Leaving the
withblock closes the file, which makes sure everything is saved before the file is read back. f.read()returns the whole file, andend=""stopsprint()adding a blank line, since the file already ends with a newline.
Other ways to write it
Using writelines()
Roll no: 14 Name: Riya Sharma Class: 12 A
writelines() writes a whole list in one call, but like write() it adds no newlines, so each string carries its own \n.
Using print() with file=
Maths 91 Physics 84 Chemistry 88
print(..., file=f) sends the text to the file instead of the screen and adds the newline for you, so text and numbers can be written together without converting them.
Try it yourself
Open the file with "a" instead of "w" and run the program twice, to see the lines added a second time instead of replaced.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
- Append Text to a File
- Read a File Line by Line
- Copy the Contents of a File
- Write a CSV File
- Read a Text File and Separate Words with #
- Count Vowels, Consonants, Uppercase and Lowercase Characters in a Text File
- Copy Lines Without the Letter 'a' to Another File
- Search a Roll Number in a Binary File
- Update Marks in a Binary File
- Store and Search User IDs and Passwords in a CSV File
All Python programs · CBSE class 12 practical file · Python exercises