open
(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=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