读和写文件python

open(filemode='r'buffering=-1encoding=Noneerrors=Nonenewline=Noneclosefd=Trueopener=None)

Open file and return a corresponding file object. If the file cannot be opened, an OSError is raised.

打开返回一个文件对象。

file is a path-like object giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. 

参数file是一个路径名,用字符串表示就行。

mode is an optional string that specifies the mode in which the file is opened.

参数mode是打开方式

 if encoding is not specified the encoding used is platform dependent:locale.getpreferredencoding(False) is called to get the current locale encoding.

如果编码方式没有指定,就用平台默认的。。。注意,最好改成“UTF-8”

import http.client
conn = http.client.HTTPSConnection("www.baidu.com")
conn.request("GET", "/")
r1 = conn.getresponse()
print(r1.status, r1.reason)
# 200 OK
data1 = r1.read()  # This will return entire content.

# 打开一个文件
f = open("baidu.txt", "w",encoding="utf-8")

f.write(bytes.decode(data1))

# 关闭打开的文件
f.close()
print(str(data1,"utf-8"))



# The following example demonstrates reading data in chunks.
# conn.request("GET", "/")
# r1 = conn.getresponse()
# while not r1.closed:
#     print(r1.read(200))  # 200 bytes
# b'<!doctype html>\n<!--[if"...

# Example of an invalid request
# conn.request("GET", "/parrot.spam")
# r2 = conn.getresponse()
# print(r2.status, r2.reason)
# 404 Not Found
# data2 = r2.read()
conn.close()

如果不指定打开文件编码为“UTF-8”就会报错:'gbk' codec can't encode character '\xbb' in position 3677: illegal multibyte sequence

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值