Python3 File write () method
Outline
write () method is used to write to the file specified string.
Before the file is closed or before the buffer is flushed, the contents of the string stored in the buffer, then you can not see in the document is written content.
grammar
write () method has the following syntax:
fileObject.write( [ str ])
parameter
str - the string to be written to the file.
return value
This method has no return value.
Examples
W3big.txt content file as follows:
1:www.w3big.com 2:www.w3big.com 3:www.w3big.com 4:www.w3big.com 5:www.w3big.com
The following example demonstrates the write () method of use:
#!/usr/bin/python3 # 打开文件 fo = open("w3big.txt", "r+") print ("文件名: ", fo.name) str = "6:www.w3big.com" # 在文件末尾写入一行 fo.seek(0, 2) line = fo.write( str ) # 读取文件所有内容 fo.seek(0,0) for index in range(6): line = next(fo) print ("文件行号 %d - %s" % (index, line)) # 关闭文件 fo.close()
The above example output is:
文件行号 0 - 1:www.w3big.com 文件行号 1 - 2:www.w3big.com 文件行号 2 - 3:www.w3big.com 文件行号 3 - 4:www.w3big.com 文件行号 4 - 5:www.w3big.com 文件行号 5 - 6:www.w3big.com
Check file contents:
$ cat w3big.txt 1:www.w3big.com 2:www.w3big.com 3:www.w3big.com 4:www.w3big.com 5:www.w3big.com 6:www.w3big.com