To open a file for writing one uses the same method a when reading files, only the
second argument to file
is different.
The content of the file is then writen using the write
or writelines
methods of the file object.
1 f = file( "tryout.txt", "w")
2
3 f.write("Hi there.")
4 f.write("How do you do?")
5
6 f.close()
Hi there.How do you do?
Doba běhu: 21.5 ms
Contrary to what one would expect, the method writelines
does not add new-line
characters at the end of individual lines. This is in order to be consistent with the
readlines
method.
1 f = file( "tryout.txt", "w")
2
3 lines1 = ["first line.", "second line.", "the third one."]
4 lines2 = ["first line.\n", "second line.\n", "the third one.\n"]
5
6 f.writelines( lines1)
7 f.writelines( lines2)
8
9 f.close()
first line.second line.the third one.first line.
second line.
the third one.
Doba běhu: 21.1 ms