注:Python版本为3.5.2
函数open():
函数功能:打开一个文件,返回一个文件读写对象,然后可以对文件进行相应读写操作。
f=open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True)
函数的参数说明:
1、file:
表示需要打开文件的相对路径(当前工作目录)或者一个绝对路径,当传入路径不存在此文件会报错。或者传入文件句柄(file descriptor)。
>>> a = open('test.txt') # 相对路径
>>> a
<_io.TextIOWrapper name='test.txt' mode='r' encoding='cp936'>
>>> a.close()
>>> a = open(r'D:\Python\Python35-32\test.txt') # 绝对路径
>>> a
<_io.TextIOWrapper name='D:\\Python\\Python35-32\\test.txt' mode='r' encoding='cp936'>
脚本:
f=open("D:\\Users\\2.txt","rt",encoding="utf-8",newline="\r\n")
a=f.fileno() #获取文件句柄
print(a)
d=open(a,closefd=False,encoding="utf-8")
print(d)
执行结果:
3
<_io.TextIOWrapper name=3 mode='r' encoding='utf-8'>
文件
2、mode:
Python中文件默认为读方式打开
f=open(url,'r',encoding='utf-8')
其他打开方式:
官方说明:
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' create a new file and open it for writing
'a' open for writing, appending to the end of the file if it exists
'b' binary mode
't' text mode (default)
'+'