【python】文件处理详解(上)

简介: 【python】文件处理详解(上)

注:最后有面试挑战,看看自己掌握了吗

文本文件

文本文件有初步存放编辑数据的能力,可以保存和共享。

建立文件

open()函数-----考虑文本名称,本身是一个字符串,需要考虑转义符号对路径或名称的影响,比如:\t被识别为制表符号

file = open('d:\t1.txt','w')
file.write('无敌坤坤爱你')
file.close()
OSError: [Errno 22] Invalid argument: 'd:\t1.txt'

解决方案:用’d:\\t1.txt' 或者 r'd:\t1.txt'

用b_new_file.close()把新建的文件关闭------?没找到

不然一直留存在内存中。

open函数详解

rwxa 与 bt+U这几个模式混合使用

注意:

open可以打开二进制文件包括--------图片、exe-----这就有了无限的想象空间,修改图片内容,往exe里面加点特殊代码~~但是对exe文件进行操作有时很有风险,需要谨慎。

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 OSError 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.)
File 是一个文本或字节字符串,提供名称(和路径)如果该文件不在当前工作目录中,则返回或文件的整数文件描述符包好了
    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.
  Open ()返回一个文件对象,其类型取决于模式,并且
通过它进行读写等标准文件操作
当 open ()用于以文本模式(‘ w’,
‘ r’、‘ wt’、‘ rt’等) ,它返回一个 TextIOWrapper
在二进制模式下,返回的类变化: 在读取二进制模式下
模式下,它返回一个 BufferedReader; 在写入二进制文件和追加二进制文件中
模式下,它返回一个 BufferedWriter,在读/写模式下,它返回
一个 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

🌸I could be bounded in a nutshell and count myself a king of infinite space.

特别鸣谢:木芯工作室 、Ivan from Russia


读写文本文件

import winreg
key = winreg.OpenKey(winreg.HKEY_CURRENT_USER,r'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders')
a_file = winreg.QueryValueEx(key,"Desktop")[0]
print(a_file)
cc=open(a_file+'\kk.txt','a')
cc.write("我是坤坤\n")
cc.close()
cc=open(a_file+'\kk.txt','r')
tt=cc.read()
print(tt)

一次写入多行

import winreg
key = winreg.OpenKey(winreg.HKEY_CURRENT_USER,r'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders')
a_file = winreg.QueryValueEx(key,"Desktop")[0]
print(a_file)
nums = ['one','two','three','four']
cc=open(a_file+'\kk.txt','a')
for getone in nums:
    cc.write(getone+'\n')
cc.close()
print("xieruchenggong")

以列表形式读取多行

import winreg
key = winreg.OpenKey(winreg.HKEY_CURRENT_USER,r'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders')
a_file = winreg.QueryValueEx(key,"Desktop")[0]
print(a_file)
nums = ['one','two','three','four']
filec=a_file+'\kk.txt'
t1 = open(a_file+'\kk.txt','r')
ccc = t1.readlines()
print(ccc)
# 连续读文件read(1)就是继续读一个字节
t1.close()
print("xieruchenggong")

在指定位置读写

import winreg
key = winreg.OpenKey(winreg.HKEY_CURRENT_USER,r'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders')
a_file = winreg.QueryValueEx(key,"Desktop")[0]
print(a_file)
nums = ['one','two','three','four']
filec=a_file+'\kk.txt'
t1 = open(a_file+'\kk.txt','r')
ccc = t1.read(4)
print(t1.tell())
print(ccc)
t1.close()
import winreg
key = winreg.OpenKey(winreg.HKEY_CURRENT_USER,r'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders')
a_file = winreg.QueryValueEx(key,"Desktop")[0]
print(a_file)
nums = ['one','two','three','four']
filec=a_file+'\kk.txt'
t1 = open(a_file+'\kk.txt','r')
ccc = t1.read(2)
print(t1.tell())
print(ccc)
t1.seek(2)
print(t1.read(5))
t1.close()

文件操作异常处理

文件操作很容易读写的文件不存在等问题,要提醒用户!

相关文章
|
Python
python文件处理-excel格式处理
python文件处理-excel格式处理
118 0
python文件处理-excel格式处理
|
存储 数据处理 索引
【100天精通python】Day27:文件与IO操作_CSV文件处理
【100天精通python】Day27:文件与IO操作_CSV文件处理
74 0
|
5月前
|
存储 运维 算法
Python文件处理(IO 技术)-2
Python文件处理(IO 技术)
|
1月前
|
存储 JSON 数据格式
Python 输入输出与文件处理: io、pickle、json、csv、os.path 模块详解
Python 输入输出与文件处理: io、pickle、json、csv、os.path 模块详解
35 0
|
1月前
|
Python
Python 中的文件处理与系统模块详解
Python 中的文件处理与系统模块详解
19 0
|
6月前
|
存储 Python
Python 文件处理
Python 文件处理
43 0
|
3月前
|
程序员 Python
深入探讨Python中的文件处理
【8月更文挑战第20天】
38 0
|
5月前
|
数据管理 Python 内存技术
python WAV音频文件处理—— (2)处理PCM音频-- waveio包
python WAV音频文件处理—— (2)处理PCM音频-- waveio包
89 15
|
5月前
|
存储 Python 内存技术
python WAV音频文件处理—— (1)读写WAV文件
python WAV音频文件处理—— (1)读写WAV文件
138 14
|
5月前
|
数据可视化 Python
python WAV音频文件处理——(3)高效处理大型 WAV 文件
python WAV音频文件处理——(3)高效处理大型 WAV 文件
113 9