案例一:python
講數組a 循環寫入名稱爲2.txt的文檔中數組
# -*-coding:utf8-*- import requests from lxml import etree a=[1,2,3,4,5,6] print(a) for i in a: f = open('C:/Users/Beckham/Desktop/python/2.txt','a') f.write('\n'+str(i)) f.close()
腳本執行結果編碼
腳本spa
f = open('C:/Users/Beckham/Desktop/python/2.txt','a')
一行'a',表明追加模式'a',能夠實現屢次寫入。即每次執行都會在上一行的基礎上,換行寫入。還有一個模式,在'w'寫入模式下,當咱們下次寫入變量時,會覆蓋本來txt文件的內容.net
若是要按行寫入,咱們只須要再字符串開頭或結尾添加換行符'\n'便可,參見code
f.write('\n'+str(i))
案例二:xml
當須要寫入的數據須要編碼的時候,不然會提示「'gbk' codec can't encode character '\xa0' in position 51: illegal multibyte sequence」blog
# -*-coding:utf8-*-
# encoding:utf-8utf-8
.....................#省略中間部分文檔
test3=test2+test#把連接和提取碼拼接成一條數據 print(test3) with open('C:/Users/Beckham/Desktop/python/1.txt', 'a',encoding='utf-8') as w: w.write('\n'+test3) w.close()
咱們就須要對打開的txt文本進行編碼處理
參考:
https://blog.csdn.net/Flying_sfeng/article/details/75009741
https://blog.csdn.net/zyx_ly/article/details/89641158