python 读取写入文件笔记

使用版本python 3.8

  • 读取时候提示编码错误
  • 比如
UnicodeDecodeError: 'gbk' codec can't decode byte xxxx :illegal multibyte sequence

3.8 可用做法是,参考

FILE_OBJECT= open('order.log','r', encoding='UTF-8')

另外一种,可能对2.x版本,我的3.8不行

FILE_OBJECT= open('order.log','rb')
  • CSV 写入会有空行,3.8 newline=” 参考
with open(output_bad, "w",newline='', encoding='UTF-8') as bad:

2.x版本是’wb+’

with open('xxx.csv','wb+',encoding='utf-8') as csvfile:#将写入方式改为wb+ 二进制写入

python 将字符串str转化成单个/一个列表list

使用的是方括号直接转化

r = 'dsadsd'
list_r = list(r)
entire_r = [r]
print('list(r) is %s'%list_r)
print('[r] is %s'%entire_r)

list(r) is ['d', 's', 'a', 'd', 's', 'd']
[r] is ['dsadsd']

尤其 CSV 的writer.writerow 传递的是list 参数,如果使用string,就存在把string分解到很多列的问题。

搜索了string转list给出都是list()函数转化,python确实是一门好用的语言

【Python】 request 错误 Failed to establish a new connection: [WinError 10061] 由于目标计算机积极拒绝,无法连接。’

最终解决办法:浏览器使用代理,需要在IE 取消勾选。

其他需要排除的:

  1. 至少要安装了request模块
  2. 本地网络是通畅的
  3. requests 的网站是正常的

错误截图如下

代码部分

import requests
r = requests.get('https://www.metaweather.com/api/location/2161842')

如果无法停用代理

请参考此篇