关于用python把中文字符写入TXT文件的问题
求大佬解答。
#_*_conding=utf-8_*_
import urllib
import urllib2
import re
url = 'http://news.xinhuanet.com/rwk/2013-02/06/c_124330585.htm'
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
headers = {'User-Agent': user_agent}
try:
request = urllib2.Request(url, headers=headers)
response = urllib2.urlopen(request)
content = response.read().decode('utf-8')
pattern = re.compile(r'<p>(.*?)<\/p>')
items = re.findall(pattern, content)
fl = open('1.txt', 'a')
for line in items:
fl.write(line)
fl.write("\n")
f1.close()
except urllib2.URLError, e:
if hasattr(e, "code"):
print e.code
if hasattr(e, "reason"):
print e.reason
报错代码:UnicodeEncodeError: 'ascii' codec can't encode characters in position 8-11: ordinal not in range(128)
相关推荐
浅谈python中对于json写入txt文件的编码问题
最近一直在研究python+selenium+beautifulsoup的爬虫,但是存入数据库还有写入txt文件里面的时候一直都是unicode编码的格式。 接下来就是各种翻阅文档,查找谷歌和度娘,但是都没有具体的说明是什么问题。 结果根据自己的代码发现,原来是一句代码写到后面去了。 name = json.dumps('中国你好', ensure_ascii=False) #重点就是这一句代码 date = time.strftime('%Y-%m-%d', time.localtime(time.time())) #此处是时间转换 f = codecs.open(date + '.txt
【Python爬虫教程】基础篇-13 文件存储
摘要:TXT文件存储、JSON文件存储、CSV文件存储
python 读取、写入txt文件的示例
写入文件 使用open()函数和write()函数 但是有两种写法,分别是’a’和’w’ ‘a’ 表示写入文件 若无该文件会直接创建一个 如果存在这个文件,会接着已有的内容的后面写入 with open('D:\\test.txt','a',encoding='utf-8') as f: text = '\n奔涌吧,后浪' f.write(text) 程序运行前: 程序运行后: ‘w’ 表示写入文件 若无该文件会直接创建一个 如果存在这个文件,里面的内容会被后面写入的内容替换掉 with open('D:\\test.txt','w',encoding='utf-8') as
解决python中 f.write写入中文出错的问题
今天小编就为大家分享一篇解决python中 f.write写入中文出错的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
python读取中文txt文本的方法
下面小编就为大家分享一篇python读取中文txt文本的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧


