python3--open函数

open函数,该函数用于文件处理

操作文件时,一般需要经历如下步骤:

  • 打开文件
  • 操作文件

一、打开文件

文件句柄 = open(‘文件路径‘, ‘模式‘)

打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。

打开文件的模式有:

  • r,只读模式(默认)。
  • w,只写模式。【不可读;不存在则创建;存在则删除内容;】
  • a,追加模式。【可读;   不存在则创建;存在则只追加内容;】

"+" 表示可以同时读写某个文件

  • r+,可读写文件。【可读;可写;可追加】
  • w+,写读
  • a+,同a

"U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)

  • rU
  • r+U

"b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)

  • rb
  • wb
  • ab

二、操作

class file(object)
    def close(self): # real signature unknown; restored from __doc__
        关闭文件
        """
        close() -> None or (perhaps) an integer.  Close the file.

        Sets data attribute .closed to True.  A closed file cannot be used for
        further I/O operations.  close() may be called more than once without
        error.  Some kinds of file objects (for example, opened by popen())
        may return an exit status upon closing.
        """

    def fileno(self): # real signature unknown; restored from __doc__
        文件描述符
         """
        fileno() -> integer "file descriptor".

        This is needed for lower-level file interfaces, such os.read().
        """
        return 0    

    def flush(self): # real signature unknown; restored from __doc__
        刷新文件内部缓冲区
        """ flush() -> None.  Flush the internal I/O buffer. """
        pass

    def isatty(self): # real signature unknown; restored from __doc__
        判断文件是否是同意tty设备
        """ isatty() -> true or false.  True if the file is connected to a tty device. """
        return False

    def next(self): # real signature unknown; restored from __doc__
        获取下一行数据,不存在,则报错
        """ x.next() -> the next value, or raise StopIteration """
        pass

    def read(self, size=None): # real signature unknown; restored from __doc__
        读取指定字节数据
        """
        read([size]) -> read at most size bytes, returned as a string.

        If the size argument is negative or omitted, read until EOF is reached.
        Notice that when in non-blocking mode, less data than what was requested
        may be returned, even if no size parameter was given.
        """
        pass

    def readinto(self): # real signature unknown; restored from __doc__
        读取到缓冲区,不要用,将被遗弃
        """ readinto() -> Undocumented.  Don‘t use this; it may go away. """
        pass

    def readline(self, size=None): # real signature unknown; restored from __doc__
        仅读取一行数据
        """
        readline([size]) -> next line from the file, as a string.

        Retain newline.  A non-negative size argument limits the maximum
        number of bytes to return (an incomplete line may be returned then).
        Return an empty string at EOF.
        """
        pass

    def readlines(self, size=None): # real signature unknown; restored from __doc__
        读取所有数据,并根据换行保存值列表
        """
        readlines([size]) -> list of strings, each a line from the file.

        Call readline() repeatedly and return a list of the lines so read.
        The optional size argument, if given, is an approximate bound on the
        total number of bytes in the lines returned.
        """
        return []

    def seek(self, offset, whence=None): # real signature unknown; restored from __doc__
        指定文件中指针位置
        """
        seek(offset[, whence]) -> None.  Move to new file position.

        Argument offset is a byte count.  Optional argument whence defaults to
(offset from start of file, offset should be >= 0); other values are 1
        (move relative to current position, positive or negative), and 2 (move
        relative to end of file, usually negative, although many platforms allow
        seeking beyond the end of a file).  If the file is opened in text mode,
        only offsets returned by tell() are legal.  Use of other offsets causes
        undefined behavior.
        Note that not all file objects are seekable.
        """
        pass

    def tell(self): # real signature unknown; restored from __doc__
        获取当前指针位置
        """ tell() -> current file position, an integer (may be a long integer). """
        pass

    def truncate(self, size=None): # real signature unknown; restored from __doc__
        截断数据,仅保留指定之前数据
        """
        truncate([size]) -> None.  Truncate the file to at most size bytes.

        Size defaults to the current file position, as returned by tell().
        """
        pass

    def write(self, p_str): # real signature unknown; restored from __doc__
        写内容
        """
        write(str) -> None.  Write string str to file.

        Note that due to buffering, flush() or close() may be needed before
        the file on disk reflects the data written.
        """
        pass

    def writelines(self, sequence_of_strings): # real signature unknown; restored from __doc__
        将一个字符串列表写入文件
        """
        writelines(sequence_of_strings) -> None.  Write the strings to the file.

        Note that newlines are not added.  The sequence can be any iterable object
        producing strings. This is equivalent to calling write() for each string.
        """
        pass

    def xreadlines(self): # real signature unknown; restored from __doc__
        可用于逐行读取文件,非全部
        """
        xreadlines() -> returns self.

        For backward compatibility. File objects now include the performance
        optimizations previously implemented in the xreadlines module.
        """
        pass

Python 2.x

python2.x

class TextIOWrapper(_TextIOBase):
    """
    Character and line based layer over a BufferedIOBase object, buffer.

    encoding gives the name of the encoding that the stream will be
    decoded or encoded with. It defaults to locale.getpreferredencoding(False).

    errors determines the strictness of encoding and decoding (see
    help(codecs.Codec) or the documentation for codecs.register) and
    defaults to "strict".

    newline controls how line endings are handled. It can be None, ‘‘,
    ‘\n‘, ‘\r‘, and ‘\r\n‘.  It works as follows:

    * On input, if newline is None, universal newlines mode is
      enabled. Lines in the input can end in ‘\n‘, ‘\r‘, or ‘\r\n‘, and
      these are translated into ‘\n‘ before being returned to the
      caller. If it is ‘‘, universal newline mode is enabled, but line
      endings are returned to the caller untranslated. If it has any of
      the other legal values, input lines are only terminated by the given
      string, and the line ending is returned to the caller untranslated.

    * On output, if newline is None, any ‘\n‘ characters written are
      translated to the system default line separator, os.linesep. If
      newline is ‘‘ or ‘\n‘, no translation takes place. If newline is any
      of the other legal values, any ‘\n‘ characters written are translated
      to the given string.

    If line_buffering is True, a call to flush is implied when a call to
    write contains a newline character.
    """
    def close(self, *args, **kwargs): # real signature unknown
        关闭文件
        pass

    def fileno(self, *args, **kwargs): # real signature unknown
        文件描述符
        pass

    def flush(self, *args, **kwargs): # real signature unknown
        刷新文件内部缓冲区
        pass

    def isatty(self, *args, **kwargs): # real signature unknown
        判断文件是否是同意tty设备
        pass

    def read(self, *args, **kwargs): # real signature unknown
        读取指定字节数据
        pass

    def readable(self, *args, **kwargs): # real signature unknown
        是否可读
        pass

    def readline(self, *args, **kwargs): # real signature unknown
        仅读取一行数据
        pass

    def seek(self, *args, **kwargs): # real signature unknown
        指定文件中指针位置
        pass

    def seekable(self, *args, **kwargs): # real signature unknown
        指针是否可操作
        pass

    def tell(self, *args, **kwargs): # real signature unknown
        获取指针位置
        pass

    def truncate(self, *args, **kwargs): # real signature unknown
        截断数据,仅保留指定之前数据
        pass

    def writable(self, *args, **kwargs): # real signature unknown
        是否可写
        pass

    def write(self, *args, **kwargs): # real signature unknown
        写内容
        pass

    def __getstate__(self, *args, **kwargs): # real signature unknown
        pass

    def __init__(self, *args, **kwargs): # real signature unknown
        pass

    @staticmethod # known case of __new__
    def __new__(*args, **kwargs): # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass

    def __next__(self, *args, **kwargs): # real signature unknown
        """ Implement next(self). """
        pass

    def __repr__(self, *args, **kwargs): # real signature unknown
        """ Return repr(self). """
        pass

    buffer = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    closed = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    encoding = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    errors = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    line_buffering = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    name = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    newlines = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    _CHUNK_SIZE = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    _finalizing = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

Python 3.x

python3.x

python:open/文件操作

open/文件操作
f=open(‘/tmp/hello‘,‘w‘)
#open(路径+文件名,读写模式)
#读写模式:r只读,r+读写,w新建(会覆盖原有文件),a追加,b二进制文件.常用模式
如:‘rb‘,‘wb‘,‘r+b‘等等

读写模式的类型有:
rU 或 Ua 以读方式打开, 同时提供通用换行符支持 (PEP 278)
w    以写方式打开,
a    以追加模式打开 (从 EOF 开始, 必要时创建新文件)
r+   以读写模式打开
w+  以读写模式打开 (参见 w )
a+     以读写模式打开 (参见 a )
rb      以二进制读模式打开
wb  以二进制写模式打开 (参见 w )
ab     以二进制追加模式打开 (参见 a )
rb+    以二进制读写模式打开 (参见 r+ )
wb+   以二进制读写模式打开 (参见 w+ )
ab+   以二进制读写模式打开 (参见 a+ )

========= ===============================================================Character Meaning--------- ---------------------------------------------------------------‘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)‘+‘       open a disk file for updating (reading and writing)‘U‘       universal newline mode (deprecated)========= ===============================================================

注意:
1、使用‘W‘,文件若存在,首先要清空,然后(重新)创建,
2、使用‘a‘模式 ,把所有要写入文件的数据都追加到文件的末尾,即使你使用了seek()指向文件的其他地方,如果文件不存在,将自动被创建。

f.read([size]) size未指定则返回整个文件,如果文件大小>2倍内存则有问题.f.read()读到文件尾时返回""(空字串)
file.readline() 返回一行
file.readline([size]) 返回包含size行的列表,size 未指定则返回全部行
for line in f: print line #通过迭代器访问
f.write("hello\n") #如果要写入字符串以外的数据,先将他转换为字符串.
f.tell() 返回一个整数,表示当前文件指针的位置(就是到文件头的比特数).
f.seek(偏移量,[起始位置])
用来移动文件指针
偏移量:单位:比特,可正可负
起始位置:0-文件头,默认值;1-当前位置;2-文件尾
f.close() 关闭文件

#!/usr/bin/env python
# Filename: using_file.py

poem=‘‘‘\Programming is funWhen the work is doneif you wanna make your work also fun: use Python!‘‘‘
f=file(‘poem.txt‘,‘w‘) # open for ‘w‘riting
f.write(poem) # write text to file
f.close() # close the file
f=file(‘poem.txt‘)

# if no mode is specified, ‘r‘ead mode is assumed by default
while True:
line=f.readline()
if len(line)==0: # Zero length indicates EOF
break
print line,
# Notice comma to avoid automatic newline added by Python
f.close()
# close the file

三、管理上下文

为了避免打开文件后忘记关闭,可以通过管理上下文,即:

with open(‘log‘,‘r‘) as f:

    ...

如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。

在Python 2.7 后,with又支持同时对多个文件的上下文进行管理,即:

with open(‘log1‘) as obj1, open(‘log2‘) as obj2:
    pass
时间: 2024-10-26 17:35:57

python3--open函数的相关文章

关于Python3中函数:

# 关于Python3中函数: - 定义 定义函数使用关键字def,后接函数名和放在圆括号()中的可选参数列表,函数内容以冒号起始并且缩进.一般格式如下:``` def 函数名(参数列表): """文档字符串""" 函数体 return [expression] ``` - 函数变量作用域 在函数内部定义的变量拥有一个局部作用域,在函数外定义的拥有全局作用域.注意:在函数内部可以引用全局变量,但无法对其赋值(除非用global进行声明).```

Python3 bytes 函数

Python3 bytes 函数  Python3 内置函数 描述 bytes 函数返回一个新的 bytes 对象,该对象是一个 0 <= x < 256 区间内的整数不可变序列.它是 bytearray 的不可变版本. 语法 以下是 bytes 的语法: class bytes([source[, encoding[, errors]]]) 参数 如果 source 为整数,则返回一个长度为 source 的初始化数组: 如果 source 为字符串,则按照指定的 encoding 将字符串

Python3 tuple 函数

Python3 tuple 函数  Python3 内置函数 描述 tuple 函数将列表转换为元组.. 语法 以下是 tuple 的语法: tuple( seq ) 参数 seq -- 要转换为元组的序列. 返回值 返回元组. 实例 以下展示了使用 tuple 的实例: 实例 >>>list1= ['Google', 'Taobao', 'Runoob', 'Baidu'] >>> tuple1=tuple(list1) >>> tuple1 ('G

(转)Python3 zip() 函数

转:http://www.runoob.com/python3/python3-func-zip.html 描述 zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的对象,这样做的好处是节约了不少的内存. 我们可以使用 list() 转换来输出列表. 如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表. zip 方法在 Python 2 和 Python 3 中的不同:在 Python 2.

python3里函数怎么样使用元组或字典作为参数调用(复制他人博客)

在python3中可以采用如下方法: 函数(*(元组)) 函数(**{字典}) 如下例子:       function(*("whither", "canada?"))               元组       function(*(1, 2 + 3))                                   元组       function(**{"a": "crunchy", "b"

Python3 reversed 函数

描述 reversed 函数返回一个反转的迭代器. 语法 以下是 reversed 的语法: reversed(seq) 参数 seq -- 要转换的序列,可以是 tuple, string, list 或 range. 返回值 返回一个反转的迭代器. 实例 以下展示了使用 tuple 的实例: 实例 #!/usr/bin/env python3 # 字符串 seqString = 'Runoob' print(list(reversed(seqString))) # 元组 seqTuple =

Python3基础-函数作用域

参考文档:https://www.runoob.com/python3/python3-namespace-scope.html 作用域 作用域就是一个 Python 程序可以直接访问命名空间的正文区域. 在一个 python 程序中,直接访问一个变量,会从内到外依次访问所有的作用域直到找到,否则会报未定义的错误. Python 中,程序的变量并不是在哪个位置都可以访问的,访问权限决定于这个变量是在哪里赋值的. 变量的作用域决定了在哪一部分程序可以访问哪个特定的变量名称 作用域类型 L(Loca

python3 print函数的用法

1. 输出字符串 >>> strHello = 'Hello World' >>> print (strHello) Hello World 2. 格式化输出整数 支持参数格式化,与C语言的printf类似 >>> strHello = "the length of (%s) is %d" %('Hello World',len('Hello World')) >>> print (strHello)the len

Python3基础 函数 关键字参数 的示例

镇场诗: 诚听如来语,顿舍世间名与利.愿做地藏徒,广演是经阎浮提. 愿尽吾所学,成就一良心博客.愿诸后来人,重现智慧清净体.------------------------------------------ code: def FunAdd(jiaOne,jiaTwo,jianOne) : '单行函数文档' return (jiaOne+jiaTwo-jianOne) #你看这么多参数,万一顺序弄混了,就尴尬了. #所以关键字参数 res=FunAdd(jiaOne=1,jiaTwo=-3,j

Python3基础 函数名.__doc__显示一个函数的单行与多行函数文档

镇场诗: 诚听如来语,顿舍世间名与利.愿做地藏徒,广演是经阎浮提. 愿尽吾所学,成就一良心博客.愿诸后来人,重现智慧清净体.------------------------------------------ code: def FunAddOne(num) : '单行函数文档' return (num+1) def FunAddTwo() : """ 多行的函数文档 很多行哦 """ print(FunAddOne.__doc__) print