Python - File writelines() Method
The Python file writelines() method is used to write the string elements of an iterable to the file.
Syntax
file.writelines(iterable)
Parameters
iterable |
Required. iterable with string items. |
Return Value
None.
Write to an Existing File
To write content in the existing file, the following file open() modes can be used.
- "a" - append mode. to append to the end of the file.
- "w" - write mode. to overwrite any existing content of the file.
The below example explains how to write content in a given file in append and write mode.
#append content to the file MyFile = open("python_test.txt", "a") #list iterable is used here MyFile.writelines(["Add more content.", "Add this content also."]) MyFile.close() #overwrite existing content of the file MyFile = open("python_test.txt", "w") #tuple iterable is used here MyFile.writelines(["Add more content.", "Add this content also."]) MyFile.close()
Write to a new File
To create a new file, the file open() function can be used in following modes:
- "a" - append mode. Opens a file in append mode and creates the file if it does not exist.
- "w" - write mode. Opens a file in write mode and creates the file if it does not exist.
- "x" - create mode. Creates a file and raises exception if it already exists.
The below example explains how to create a new file called NewFile if it does not exist using append, write and create mode.
#Creates a file "MyFile" if it does not exist MyFile = open("python_test.txt", "a") MyFile.writelines(["Add more content.", "Add this content also."]) MyFile.close() #Creates a file "MyFile" if it does not exist MyFile = open("python_test.txt", "w") MyFile.writelines(["Add more content.", "Add this content also."]) MyFile.close() #Creates a file "MyFile" if it does not exist MyFile = open("python_test.txt", "x") MyFile.writelines(["Add more content.", "Add this content also."]) MyFile.close()
❮ Python File Handling Methods