Writing a file
We have the following methods for writing the content of a file:
- write() : To write a string into a file.
- writelines() : To write a list of strings into a file.
Access modes for writing
Mode | |
---|---|
w | Write a file. If file already exists, it truncates the file. |
w+ | Read and Write |
wb | Write in binary file |
a | Append content to file. If the file already exists, new content will be appended to the existing content. |
a+ | Read and append. |
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()
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()