Python - Write to File



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])

Writing to a New File

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 to a New File 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')

Writing to an Existing 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

Writing to a File in Reading and Writing Modes

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
Advertisements