Python资料之文件IO操作

这篇博客详细介绍了Python 3.5.2中的文件IO操作,包括open()函数的参数说明,如mode、buffering、encoding等,并提供了多个脚本示例,展示了文件的读写、关闭、属性和方法,如file.close()、file.read()、file.write()等。
摘要由CSDN通过智能技术生成

注: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)
    '+'       
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值