Skip to content

Python Write File (Python Write to Text File example)

  • by

To Write File in python you must rely on the built-in open() function. Open function is an inbuilt method, you don’t need to add the extra library. In this tutorial, you will learn how to python write a file in detail.

Python Write File (Python Write to Text File example)

How to Python Write File?

In order to open an existing file and write it, you will need to use a python in the build method (function) Open to get a file object. The file object has a function and attributes to data/content write and update etc.

Syntax:

Where file_obj is a variable to hold the file object. The mode argument is required ‘w’ because the default value of ‘r’ will be assumed if it is omitted. Where ‘w ‘value stands for write mode.

#Opening file
file_obj  = open("filename", "mode")
# write text into file 
file_obj.write("Hello file")

Modes

  • r Read mode Open text file for reading (default option) in open function. The stream is positioned at the beginning of the file.
  • w – Write mode  (Edit and write new data into the file). The stream is positioned at the beginning of the file.
  • a – Appending mode Open for writing. The file is created if it does not exist. The stream is positioned at the end of the file.
  • r+ Read and write mode  Open for reading and writing. The stream is positioned at the beginning of the file.

Examples:

Assume we have the empty “testFile.txt” file, located in the same folder as Python.

Now writing the file. w – Write mode

f = open("testFile.txt", "w")
f.write("Hello file")

Output: in the text file

Python Write File Write mode

Writing the file. a – Appending mode

f = open("testFile.txt", "a")
f.write(" Appending mode")

Output: in the text file, text added in last. You can use a read method to print() text in the console.

For a complete tutorial in detail must read Append File On Existing File.

[WpProQuiz 2]

Do comment if you have any doubt and question on this tutorial.

Note : This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6

Python 3.7

All Examples of Python Write to File OR Text File are in Python 3, so it may change its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading