Editor

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

write_to_file.py
lines = ["Roll no: 14", "Name: Riya Sharma", "Class: 12 A"]
# or: lines = [input("Enter line 1: "), input("Enter line 2: ")]
# "w" creates the file, or empties it if it already exists
with open("student.txt", "w") as f:
for line in lines:
f.write(line + "\n") # write() does not add a newline by itself
print("Wrote", len(lines), "lines to student.txt")
# Read the file back to check what was saved
with open("student.txt", "r") as f:
print("File contents:")
print(f.read(), end="")
Output
Wrote 3 lines to student.txt
File contents:
Roll no: 14
Name: Riya Sharma
Class: 12 A

How it works

  1. open("student.txt", "w") opens the file for writing and creates it if needed; if it already exists, its old contents are erased first.
  2. f.write() writes exactly the string it is given, so "\n" is added to put each item on its own line.
  3. write() only accepts strings, so a number has to be turned into text with str() before it is written.
  4. Leaving the with block closes the file, which makes sure everything is saved before the file is read back.
  5. f.read() returns the whole file, and end="" stops print() adding a blank line, since the file already ends with a newline.

Other ways to write it

Using writelines()

Using writelines()
lines = ["Roll no: 14\n", "Name: Riya Sharma\n", "Class: 12 A\n"]
with open("student.txt", "w") as f:
f.writelines(lines) # writes every string in the list, as it is
with open("student.txt", "r") as f:
print(f.read(), end="")
Output
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=

Using print() with file=
marks = {"Maths": 91, "Physics": 84, "Chemistry": 88}
with open("marks.txt", "w") as f:
for subject, score in marks.items():
print(subject, score, file=f) # numbers need no str()
with open("marks.txt", "r") as f:
print(f.read(), end="")
Output
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.

All Python programs · CBSE class 12 practical file · Python exercises