Latest web development tutorials

Python3 File write() 方法

Python3 File(文件) 方法 Python3 File(文件)方法


概述

write()方法用於向文件中寫入指定字符串。

在文件關閉前或緩衝區刷新前,字符串內容存儲在緩衝區中,這時你在文件中是看不到寫入的內容的。

語法

write() 方法語法如下:

fileObject.write( [ str ])

參數

  • str --要寫入文件的字符串。

返回值

該方法沒有返回值。

實例

文件w3big.txt 的內容如下:

1:www.w3big.com
2:www.w3big.com
3:www.w3big.com
4:www.w3big.com
5:www.w3big.com

以下實例演示了write() 方法的使用:

#!/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()

以上實例輸出結果為:

文件行号 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

查看文件內容:

$ 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

Python3 File(文件) 方法 Python3 File(文件)方法