(014)我们一起学Python;文件操作

这一节我们来学习文件的操作,对于经常学习嵌入式的童鞋可能不如学习PC编程语言

的童鞋对此熟悉,文件是个好东西,大家一起来学习吧!

首先是打开文件操作,使用open()函数,函数格式如下:

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
    Open file and return a stream.  Raise IOError upon failure.


    file is either a text or byte string giving the name (and the path
    if the file isn't in the current working directory) of the file to
    be opened or an integer file descriptor of the file to be    wrapped. (If a file descriptor is given, it is closed when the

    returned I/O object is closed, unless closefd is set to False.)

我们主要用的是前两个参数,第一个是文件路径,第二个是打开模式(究竟是躺着打开还是趴着打开),第一个参数需要用单引号括起来,第二个参数如下:


#以参数 a 打开文件,如果没有这个文件则创建新文件,新创建的文件去打开的时候显示not readable

 f = open('F:/test.txt','a')
>>> f.read()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
io.UnsupportedOperation: not readable

>>> f            # f 输入文件句柄会返回文件信息,name是文件路径,mode模式,encoding是编码格式。
<_io.TextIOWrapper name='F:/test.txt' mode='a' encoding='cp936'>


猜你喜欢

转载自blog.csdn.net/weixin_34981646/article/details/80838673