Python File writelines() method
Overview
writelines() This method writes a sequence of strings to a file.
This sequence of strings can be produced by an iterable object, such as a list of strings.
Newlines require specifying the newline character \n.
Syntax
The writelines() method syntax is as follows:
fileObject.writelines( [ str ])
Parameters
-
str -- the sequence of strings to write to the file.
Return Value
This method has no return value.
Example
The following example shows how to use the writelines() method:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# Open file
fo = open("test.txt", "w")
print "文件名为: ", fo.name
seq = ["Runoob Tutorial 1\n", "Runoob Tutorial 2"]
fo.writelines( seq )
# Close file
fo.close()
The output of the above example is:
文件名为: test.txt
View the file contents:
$ cat test.txt
Runoob Tutorial 1
Runoob Tutorial 2
Python File methods