Python row write the variable text txt

Case number one:

Speak array write a name for the document circulating in 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()

Script execution results

script

f = open('C:/Users/Beckham/Desktop/python/2.txt','a')

Line 'a', the representative append mode 'a', may be implemented multiple writing. That is, each will be executed on the basis of the previous line, line written. There is also a mode in 'w' write mode, the next time when we write variables will overwrite the contents of the original txt file

 

To carry the line is written, we again just at the beginning or end of the string to add newline '\ n' to see

f.write('\n'+str(i))

 

Case II:

When writing the data to be encoded, otherwise it will prompt " 'gbk' codec can not encode character '\ xa0' in position 51: illegal multibyte sequence"

# -*-coding:utf8-*-
# encoding:utf-8

 

..................... intermediate portion omitted #

Test test2 + = Test3 # the link and assembled into a data extraction code 
        Print (Test3) 
        with Open ( ' C: /Users/Beckham/Desktop/python/1.txt ' , ' A ' , encoding = ' UTF-. 8 ' ) AS W: 
            w.write ( ' \ n- ' + Test3) 
            w.close ()

We need to open txt text encoding process

reference:

https://blog.csdn.net/Flying_sfeng/article/details/75009741

https://blog.csdn.net/zyx_ly/article/details/89641158

 

Guess you like

Origin www.cnblogs.com/becks/p/11372283.html