Writing a file in Python


Writing a file

We have the following methods for writing the content of a file:

  1. write() : To write a string into a file.
  2. writelines() : To write a list of strings into a file.

Access modes for writing

Mode
wWrite a file. If file already exists, it truncates the file.
w+Read and Write
wbWrite in binary file
aAppend content to file. If the file already exists, new content will be appended to the existing content.
a+Read and append.
File modes

write() method

The write() method is used to write the string to the file.

Writing the file.

In [1]:
file = open("readme.txt","w")
file.write("Welcome to Logical Python.")
file.close()

Verifying the content of file.

In [2]:
file = open("readme.txt","r")
print(file.read())
file.close()
Welcome to Logical Python.

whitelines() method

The writelines() method is used to write the list of strings to the file.

Writing the content in form of list to file.

In [1]:
content_list = ["Welcome to Logical Python.\n", "Best website to Learn Python.\n", "Thanks for Visiting."]

file = open("readme.txt","w")
file.writelines(content_list)
file.close()

Verifying the content of file.

In [2]:
file = open("readme.txt","r")
print(file.read())
file.close()
Welcome to Logical Python.
Best website to Learn Python.
Thanks for Visiting.