Get The Most Affordable Hosting in the World!

Starting at just $1.87/month, Vercaa offers unbeatable pricing for world-class web hosting services.

Fast, reliable, and secure hosting to power your website without breaking the bank. Plus, enjoy a free CDN for faster loading times worldwide!

Get Started Now!

To write data to a file in Python, you need to open a file. Any object that interacts with input and output steam is called File object. Python's built-in function open() returns a file object.

fileObject = open(file_name [, access_mode][, buffering])

After you obtain the file object with the open() function, you can use the write() method to write any string to the file represented by the file object. It is important to note that Python strings can have binary data and not just text.

The write() method does not add a newline character ('\n') to the end of the string.

Syntax

fileObject.write(string)

Here, passed parameter is the content to be written into the opened file.

Example

# Open a file fo = open("foo.txt", "w") fo.write( "Python is a great language.\nYeah its great!!\n") # Close opened file fo.close()

The above method would create foo.txt file and would write given content in that file and finally it would close that file. The program shows no output as such, although if you would open this file with any text editor application such as Notepad, it would have the following content −

Python is a great language.
Yeah its great!!

Writing in Binary Mode

By default, read/write operation on a file object are performed on text string data. If we want to handle files of different other types such as media (mp3), executables (exe), pictures (jpg) etc., we need to add 'b' prefix to read/write mode.

Following statement will convert a string to bytes and write in a file.

f=open('test.bin', 'wb') data=b"Hello World" f.write(data) f.close()

Conversion of text string to bytes is also possible using encode() function.

data="Hello World".encode('utf-8')

Appending to a File

When any existing file is opened in 'w' mode to store additional text, its earlier contents are erased. Whenever a file is opened with write permission, it is treated as if it is a new file. To add data to an existing file, use 'a' for append mode.

Syntax

fileobject = open(file_name,"a")

Example

# Open a file in append mode fo = open("foo.txt", "a") text = "TutorialsPoint has a fabulous Python tutorial" fo.write(text) # Close opened file fo.close()

When the above program is executed, no output is shown, but a new line is appended to foo.txt. To verify, open with a text editor.

Python is a great language.
Yeah its great!!
TutorialsPoint has a fabulous Python tutorial

Using the w+ Mode

When a file is opened for writing (with 'w' or 'a'), it is not possible to perform write operation at any earlier byte position in the file. Th 'w+' mode enables using write() as well as read() methods without closing a file. The File object supports seek() unction to rewind the stream to any desired byte position.

Following is the syntax for seek() method −

fileObject.seek(offset[, whence])

Parameters

  • offset − This is the position of the read/write pointer within the file.

  • whence − This is optional and defaults to 0 which means absolute file positioning, other values are 1 which means seek relative to the current position and 2 means seek relative to the file's end.

Let us use the seek() method to show how simultaneous read/write operation on a file can be done.

Example

The following program opens the file in w+ mode (which is a read-write mode), adds some data. The it seeks a certain position in file and overwrites its earlier contents with new text.

# Open a file in read-write mode fo=open("foo.txt","w+") fo.write("This is a rat race") fo.seek(10,0) data=fo.read(3) fo.seek(10,0) fo.write('cat') fo.close()

Output

If we open the file in Read mode (or seek the starting position while in w+ mode), and read the contents, it shows −

This is a cat race



The End! should you have any inquiries, we encourage you to reach out to the Vercaa Support Center without hesitation.
Hjälpte svaret dig? 1 användare blev hjälpta av detta svar (1 Antal röster)