python中file是什么意思_Python中的file和open用法详解

file和open有什么区别?

file是一个类,而用open函数打开后是返回一个file对象。

file1 = file("aa.txt")

file2 = open("aa.txt")#这个时候返回的是跟file1一样的对象,都可以对aa.txt进行读取,修改。

暂时发现貌似没多大区别,习惯上喜欢用open。

Python 2 里基本没区别。Python 3 里没 file。

Python 2 里,file 是文件对象。open 是返回新创建的文件对象的内建函数,相当于:

def open(*args, **kwargs):

return file(*args, **kwargs)

它真实的定义是:

static PyObject *

builtin_open(PyObject *self, PyObject *args, PyObject *kwds)

{

return PyObject_Call((PyObject*)&PyFile_Type, args, kwds);

}

所以 file 也是能够创建文件的。

file和open用法

help(file) help(open)

老规矩先看一下内置的帮助文档怎么描述file和open,毕竟官方文档是最直接最准确的描述。

Help on class file in module __builtin__:

class file(object)

|  file(name[, mode[, buffering]]) -> file object

|

|  Open a file.  The mode can be 'r', 'w' or 'a' for reading (default),

|  writing or appending.  The file will be created if it doesn't exist

|  when opened for writing or appending; it will be truncated when

|  opened for writing.  Add a 'b' to the mode for binary files.

|  Add a '+' to the mode to allow simultaneous reading and writing.

|  If the buffering argument is given, 0 means unbuffered, 1 means line

|  buffered, and larger numbers specify the buffer size.  The preferred way

|  to open a file is with the builtin open() function.

|  Add a 'U' to mode to open the file for input with universal newline

|  support.  Any line ending in the input file will be seen as a '\n'

|  in Python.  Also, a file so opened gains the attribute 'newlines';

|  the value for this attribute is one of None (no newline read yet),

|  '\r', '\n', '\r\n' or a tuple containing all the newline types seen.

简单来说就是file是一个类,使用 file('file_name', 'r+') 这种方式打开文件,返回一个file对象,以写模式打开文件不存在则会被创建。但是更推荐使用内置函数open()来打开一个文件,所以我们再看一下open()的介绍:

Help on built-in function open in module __builtin__:

open(...)

open(name[, mode[, buffering]]) -> file object

Open a file using the file() type, returns a file object.  This is the

preferred way to open a file.  See file.__doc__ for further information.

(END)

首先open是内置函数,使用方式是open('file_name', mode, buffering),返回值也是一个file对象,同样,以写模式打开文件如果不存在也会被创建一个新的。

使用实例

In [8]: f1 = open('test.py')

In [9]: f1.

f1.close       f1.fileno      f1.name        f1.readinto    f1.softspace   f1.writelines

f1.closed      f1.flush       f1.newlines    f1.readline    f1.tell        f1.xreadlines

f1.encoding    f1.isatty      f1.next        f1.readlines   f1.truncate

f1.errors      f1.mode        f1.read        f1.seek        f1.write

In [9]: f1.rea

f1.read       f1.readinto   f1.readline   f1.readlines

In [9]: f1.readli

f1.readline   f1.readlines

In [9]: f1.readlines()

Out[9]:

['import logging\n',

'\n',

"logging.basicConfig(filename='test.log', level=logging.INFO)\n",

"logging.info('Started')\n",

"print 'x' + 1\n",

"logging.info('Finished')\n"]

In [10]: f1.cl

f1.close   f1.closed

In [10]: f1.close()

In [11]: f2 = file('test.py')

In [12]: f2.

f2.close       f2.fileno      f2.name        f2.readinto    f2.softspace   f2.writelines

f2.closed      f2.flush       f2.newlines    f2.readline    f2.tell        f2.xreadlines

f2.encoding    f2.isatty      f2.next        f2.readlines   f2.truncate

f2.errors      f2.mode        f2.read        f2.seek        f2.write

In [12]: f2.read

f2.read       f2.readinto   f2.readline   f2.readlines

In [12]: f2.readli

f2.readline   f2.readlines

In [12]: f2.readlines()

Out[12]:

['import logging\n',

'\n',

"logging.basicConfig(filename='test.log', level=logging.INFO)\n",

"logging.info('Started')\n",

"print 'x' + 1\n",

"logging.info('Finished')\n"]

In [13]: f2.cl

f2.close   f2.closed

In [13]: f2.closed()

---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

in ()

----> 1 f2.closed()

TypeError: 'bool' object is not callable

In [14]: f2.closed

Out[14]: False

In [15]: f2.close()

# 打开不存在的文件

In [18]: f3 = file('txt.txt', 'r+')

---------------------------------------------------------------------------

IOError                                   Traceback (most recent call last)

in ()

----> 1 f3 = file('txt.txt', 'r+')

IOError: [Errno 2] No such file or directory: 'txt.txt'

In [19]: f3 = file('txt.txt', 'w+')

可以看出来使用的时候区别也不大,不过注意Py3中已经没有了file~这可能也是推荐使用open的一个很重要的原因吧

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Pythonopen()函数用于打开文件并返回一个文件对象,可以用来读取或写入文件。open()函数的基本语法为: ```python open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) ``` 其file参数表示要打开的文件名,可以是一个字符串类型的文件路径或文件描述符;mode参数表示打开文件的模式,有读取('r')、写入('w')、追加('a')等模式;buffering参数表示缓冲区大小,-1表示使用默认缓冲区大小;encoding参数表示文件编码方式,如果不指定则使用系统默认编码方式;errors参数表示编码错误处理方式;newline参数表示换行符设置,如果不指定则使用系统默认换行符;closefd参数表示是否关闭文件描述符,如果为True,则在文件关闭时同时关闭文件描述符;opener参数表示自定义打开方式。 常见的打开文件模式有: - 'r':只读模式,文件必须存在,否则抛出异常。 - 'w':只写模式,文件不存在时会被创建,若文件已存在则覆盖原内容。 - 'a':追加模式,文件不存在时会被创建,若文件已存在则在文件末尾添加新内容。 例如,打开一个名为“test.txt”的文件并读取其的内容,可以使用以下代码: ```python with open('test.txt', 'r') as f: content = f.read() print(content) ``` 其,使用了with语句来自动关闭文件,将文件内容读取到content变量并输出。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值