Python基础学习简记--文件与文件系统(Day9)

本文是Python基础学习的第九天,主要介绍了文件与文件系统。内容涵盖open()方法的使用,file对象的常见方法,如close(), read(), readline()等;os模块的常用功能,如获取当前工作目录、创建和删除目录等;还讨论了序列化与反序列化,特别是pickle模块的应用。" 129730270,17963498,ABAQUS多步骤分析:数据传递与初始场导入,"['有限元分析', 'ABAQUS教程', '数值模拟', '工程计算', '材料模拟']
摘要由CSDN通过智能技术生成

Python基础学习简记–文件与文件系统(Day9)

1、open()方法
def open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True): # known special case of open
    """
    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.)
    
    mode is an optional string that specifies the mode in which the file
    is opened. It defaults to 'r' which means open for reading in text
    mode.  Other common values are 'w' for writing (truncating the file if
    it already exists), 'x' for creating and writing to a new file, and
    'a' for appending (which on some Unix systems, means that all writes
    append to the end of the file regardless of the current seek position).
    In text mode, if encoding is not specified the encoding used is platform
    dependent: locale.getpreferredencoding(False) is called to get the
    current locale encoding. (For reading and writing raw bytes use binary
    mode and leave encoding unspecified.) The available modes are:
    
    ========= ===============================================================
    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)
    ========= ===============================================================
    
    The default mode is 'rt' (open for reading text). For binary random
    access, the mode 'w+b' opens and truncates the file to 0 bytes, while
    'r+b' opens the file without truncation. The 'x' mode implies 'w' and
    raises an `FileExistsError` if the file already exists.
    
    Python distinguishes between files opened in binary and text modes,
    even when the underlying operating system doesn't. Files opened in
    binary mode (appending 'b' to the mode argument) return contents as
    bytes objects without any decoding. In text mode (the default, or when
    't' is appended to the mode argument), the contents of the file are
    returned as strings, the bytes having been first decoded using a
    platform-dependent encoding or using the specified encoding if given.
    
    'U' mode is deprecated and will raise an exception in future versions
    of Python.  It has no effect in Python 3.  Use newline to control
    universal newlines mode.
    
    buffering is an optional integer used to set the buffering policy.
    Pass 0 to switch buffering off (only allowed in binary mode), 1 to select
    line buffering (only usable in text mode), and an integer > 1 to indicate
    the size of a fixed-size chunk buffer.  When no buffering argument is
    given, the default buffering policy works as follows:
    
    * Binary files are buffered in fixed-size chunks; the size of the buffer
      is chosen using a heuristic trying to determine the underlying device's
      "block size" and falling back on `io.DEFAULT_BUFFER_SIZE`.
      On many systems, the buffer will typically be 4096 or 8192 bytes long.
    
    * "Interactive" text files (files for which isatty() returns True)
      use line buffering.  Other text files use the policy described above
      for binary files.
    
    encoding is the name of the encoding used to decode or encode the
    file. This should only be used in text mode. The default encoding is
    platform dependent, but any encoding supported by Python can be
    passed.  See the codecs module for the list of supported encodings.
    
    errors is an optional string that specifies how encoding errors are to
    be handled---this argument should not be used in binary mode. Pass
    'strict' to raise a ValueError exception if there is an encoding error
    (the default of None has the same effect), or pass 'ignore' to ignore
    errors. (Note that ignoring encoding errors can lead to data loss.)
    See the documentation for codecs.register or run 'help(codecs.Codec)'
    for a list of the permitted encoding error strings.
    
    newline controls how universal newlines works (it only applies to text
    mode). 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 closefd is False, the underlying file descriptor will be kept open
    when the file is closed. This does not work when a file name is given
    and must be True in that case.
    
    A custom opener can be used by passing a callable as *opener*. The
    underlying file descriptor for the file object is then obtained by
    calling *opener* with (*file*, *flags*). *opener* must return an open
    file descriptor (passing os.open as *opener* results in functionality
    similar to passing None).
    
    open() returns a file object whose type depends on the mode, and
    through which the standard file operations such as reading and writing
    are performed. When open() is used to open a file in a text mode ('w',
    'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open
    a file in a binary mode, the returned class varies: in read binary
    mode, it returns a BufferedReader; in write binary and append binary
    modes, it returns a BufferedWriter, and in read/write mode, it returns
    a BufferedRandom.
    
    It is also possible to use a string or bytearray as a file for both
    reading and writing. For strings StringIO can be used like a file
    opened in a text mode, and for bytes a BytesIO can be used like a file
    opened in a binary mode.
    """
    pass

注意:使用 open() 方法一定要对应的调用 close() 方法。

open() 函数常用形式是接收两个参数:文件名(file)和模式(mode)。

2、file对象方法

几个常用的对象方法:

  1. file.close():关闭文件。
  2. file.read([size]):从文件读取指定的字节数,如果未给定或为负则读取所有。
  3. file.readline([size]):读取整行,包括 “\n” 字符。
  4. file.readlines([sizeint]):读取所有行并返回列表,若给定sizeint>0,返回总和大约为sizeint字节的行, 实际读取值可能比 sizeint 较大, 因为需要填充缓冲区。
  5. file.seek(offset[, whence]):移动文件读取指针到指定位置
  6. file.tell():返回文件当前位置。
  7. file.write(str):将字符串写入文件,返回的是写入的字符长度。
  8. file.writelines(sequence):向文件写入一个序列字符串列表,如果需要换行则要自己加入每行的换行符。
3、os模块

python的os模块提供了一个可以跨平台的通用的文件和路径的操作方法,可以非常方便的处理相关问题。os模块的方法很细很多,简单介绍常用的几个处理方法如下:

  1. os.getcwd():返回当前工作目录
    os.getenv():读取环境变量
  2. os.listdir(path):返回path指定的文件夹包含的文件或文件夹的名字的列表。
    os.mkdir(path):创建一个目录。
    os.rmdir(path):删除path指定的空目录,如果目录非空,则抛出一个OSError异常。
    os.makedirs(path):递归文件夹创建函数。
    os.removedirs(path):递归删除目录。
    os.chdir(path):改变当前工作目录
    os.rename(src, dst):重命名文件或目录,从 src 到 dst
  3. os.path.exists(path) 路径存在则返回True,路径损坏返回False
    os.path.isfile(path) 判断路径是否为文件
    os.path.isdir(path) 判断路径是否为目录
    os.path.abspath(path) 返回绝对路径
    os.path.basename(path) 返回文件名
    os.path.dirname(path) 返回文件路径
    os.path.getsize(path) 返回文件大小,如果文件不存在就返回错误
    os.path.join(path1[, path2[, …]]) 把目录和文件名合成一个路径
4、序列化与反序列化

Python 的 pickle 模块是用来将python数据进行序列化和反序列化以方便的进行存储和读取的模块。
常用有4个函数:

  1. pickle.dump(obj, file, [,protocol]) 将obj对象序列化存入已经打开的file中。
    protocol:序列化使用的协议。如果该项省略,则默认为0。如果为负值或HIGHEST_PROTOCOL,则使用最高的协议版本。
  2. pickle.load(file) 将file中的对象序列化读出。
  3. pickle.dumps(obj[, protocol])将obj对象序列化为string形式,而不是存入文件中。
  4. pickle.loads(string)从string中读出序列化前的obj对象。
5、参考文献

https://www.runoob.com/python3/python3-file-methods.html
https://mp.weixin.qq.com/s/ELDaW91e7m_MblN02OXcvQ

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值