python文件处理

python程序设计

一、填空题

  1. 文件对象的flush()方法用来把缓冲区的内容写入文件,但不关闭文件。
  2. os.path模块中的isfile(path)方法用来测试指定的路径是否为文件。
  3. os模块的listdir方法用来返回包含指定文件夹中所有文件和子文件夹的列表。
  4. 使用open("f1.txt","a")打开文件时,若f1文件不存在,则创建f1.txt文件。

二、其他

  1. 假设有一个英文文本文件,编写程序读取其内容,并将其中的大写字母变为小写字母,小写字母变为大写字母。
  2. 编写程序,将包含学生成绩的字典保存为二进制文件,然后再读取内容并显示。
  3. 编写代码,将当前工作目录修改为“c:\”,并验证,最后将当前工作目录恢复为原来的目录。
  4. 编写程序,用户输入一个目录和一个文件名,搜索该目录及其子目录中是否存在该文件。

三、代码

代码1

# 假设有一个英文文本文件,编写程序读取其内容,
# 并将其中的大写字母变为小写字母,小写字母变为大写字母。
with open('sample.txt','r+') as fp:
    for line in fp:
        print(line.swapcase())
  • 文件内容
    Taotao is a beautiful girl, and she loves a handsome boy named Jianle in wechat all her life.

  • 运行效果
    tAOTAO IS A BEAUTIFUL GIRL, AND SHE LOVES A HANDSOME BOY NAMED jIANLE IN WECHAT ALL HER LIFE.

  • 代码分析

    • open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
      • (file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
        Open file and return a corresponding file object. If the file cannot be opened, an OSError is raised.
      • file is a path-like object giving the pathname (absolute or relative to 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 exclusive creation 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' open for exclusive creation, failing if the file already exists
    '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)
      * `For example:`
        ```
           >>> import os
           >>> dir_fd = os.open('somedir', os.O_RDONLY)
           >>> def opener(path, flags):
           ...     return os.open(path, flags, dir_fd=dir_fd)
           ...
           >>> with open('spamspam.txt', 'w', opener=opener) as f:
           ...     print('This will be written to somedir/spamspam.txt', file=f)
           ...
           >>> os.close(dir_fd)  # don't leak a file descriptor
       ```
    
    • bytes.swapcase()
    • bytearray.swapcase()
      • Return a copy of the sequence with all the lowercase ASCII characters converted to their corresponding uppercase counterpart and vice-versa.
      • For example:
        >>> b'Hello World'.swapcase()
        b'hELLO wORLD'
        

代码2

# 编写程序,将包含学生成绩的字典保存为二进制文件,然后再读取内容并显示。
import pickle
taiyi={'语文':120,'数学':130,'英语':100,'综合':250}
qinyun={'语文':120,'数学':100,'英语':150,'综合':260}
data=(taiyi,qinyun)
with open('score.dat','wb') as f:
    try:
        pickle.dump(len(data),f)
        for item in data:
            pickle.dump(item,f)
    except:
        print('写文件异常')

with open('score.dat','rb') as f:
    n=pickle.load(f)
    for i in range(n):
        x=pickle.load(f)
        print(x)
  • 运行结果

    (如果与代码同一目录下没有score.dat,则会自动创建),score.dat文件的内容
    €K.€}q (X 璇枃qKxX 鏁板qK俋 鑻辫qKdX 缁煎悎qK鷘.€}q (X 璇枃qKxX 鏁板qKdX 鑻辫qK朮 缁煎悎qMu.
    输出窗口内容:

  • 代码分析
    • pickle
      • The pickle module implements binary protocols for serializing and de-serializing a Python object structure. “Pickling” is the process whereby a Python object hierarchy is converted into a byte stream, and “unpickling” is the inverse operation, whereby a byte stream (from a binary file or bytes-like object) is converted back into an object hierarchy. Pickling (and unpickling) is alternatively known as “serialization”, “marshalling,” [1] or “flattening”; however, to avoid confusion, the terms used here are “pickling” and “unpickling”.
      • example
        import builtins
        import io
        import pickle
        
        safe_builtins = {
            'range',
            'complex',
            'set',
            'frozenset',
            'slice',
        }
        
        class RestrictedUnpickler(pickle.Unpickler):
        
            def find_class(self, module, name):
                # Only allow safe classes from builtins.
                if module == "builtins" and name in safe_builtins:
                    return getattr(builtins, name)
                # Forbid everything else.
                raise pickle.UnpicklingError("global '%s.%s' is forbidden" %
                                             (module, name))
        
        def restricted_loads(s):
            """Helper function analogous to pickle.loads()."""
            return RestrictedUnpickler(io.BytesIO(s)).load()
        
      • A sample usage of our unpickler working has intended:
        >>> restricted_loads(pickle.dumps([1, 2, range(15)]))
        [1, 2, range(0, 15)]
        >>> restricted_loads(b"cos\nsystem\n(S'echo hello world'\ntR.")
        Traceback (most recent call last):
          ...
        pickle.UnpicklingError: global 'os.system' is forbidden
        >>> restricted_loads(b'cbuiltins\neval\n'
        ...                  b'(S\'getattr(__import__("os"), "system")'
        ...                  b'("echo hello world")\'\ntR.')
        Traceback (most recent call last):
          ...
        pickle.UnpicklingError: global 'builtins.eval' is forbidden
        
      • pickle.dumps(obj, protocol=None, *, fix_imports=True)
        • Return the pickled representation of the object as a bytes object, instead of writing it to a file.
        • Arguments protocol and fix_imports have the same meaning as in dump().
      • pickle.load(file, *, fix_imports=True, encoding="ASCII", errors="strict")
        • Read a pickled object representation from the open file object file and return the reconstituted object hierarchy specified therein. This is equivalent to Unpickler(file).load().
        • The protocol version of the pickle is detected automatically, so no protocol argument is needed. Bytes past the pickled object’s representation are ignored.
        • The argument file must have two methods, a read() method that takes an integer argument, and a readline() method that requires no arguments. Both methods should return bytes. Thus file can be an on-disk file opened for binary reading, an io.BytesIO object, or any other custom object that meets this interface.
        • Optional keyword arguments are fix_imports, encoding and errors, which are used to control compatibility support for pickle stream generated by Python 2. If fix_imports is true, pickle will try to map the old Python 2 names to the new names used in Python 3. The encoding and errors tell pickle how to decode 8-bit string instances pickled by Python 2; these default to ‘ASCII’ and ‘strict’, respectively. The encoding can be ‘bytes’ to read these 8-bit string instances as bytes objects. Using encoding='latin1' is required for unpickling NumPy arrays and instances of datetime, date and time pickled by Python 2.

代码3

# 编写代码,将当前工作目录修改为“c:\”,并验证,
# 最后将当前工作目录恢复为原来的目录。
import os
import os.path
s=os.getcwd()
print(s)
os.chdir('C:\\')
print(os.getcwd())
os.chdir(s)
print(os.getcwd())
  • 运行效果
    G:\zuoye\2021\Python实验\cater10
    C:\
    G:\zuoye\2021\Python实验\cater10
    
  • 代码分析
    • This module provides a portable way of using operating system dependent functionality. If you just want to read or write a file see open(), if you want to manipulate paths, see the os.path module, and if you want to read all the lines in all the files on the command line see the fileinput module. For creating temporary files and directories see the tempfile module, and for high-level file and directory handling see the shutil module.
    • This module implements some useful functions on pathnames. To read or write files see open(), and for accessing the filesystem see the os module. The path parameters can be passed as either strings, or bytes. Applications are encouraged to represent file names as (Unicode) character strings. Unfortunately, some file names may not be representable as strings on Unix, so applications that need to support arbitrary file names on Unix should use bytes objects to represent path names. Vice versa, using bytes objects cannot represent all file names on Windows (in the standard mbcs encoding), hence Windows applications should use string objects to access all files.

代码4

# 编写程序,用户输入一个目录和一个文件名,
# 搜索该目录及其子目录中是否存在该文件。
from os import listdir
from os.path import join,isfile,isdir

def listDirDepthFirst(directory,f):
    for subPath in listdir(directory):
        if subPath==f:
            print('存在')
            break
        path=join(directory,subPath)
        if isdir(path):
            listDirDepthFirst(path,f)
# 测试
if __name__=='__main__':
    listDirDepthFirst('G:/zuoye/2021/Python实验/cater10','example4.py')
  • 运行结果
    存在

  • 代码分析

    • os.listdir(path='.')
      • Return a list containing the names of the entries in the directory given by path. The list is in arbitrary order, and does not include the special entries '.' and '..' even if they are present in the directory.
      • path may be a path-like object. If path is of type bytes (directly or indirectly through the PathLike interface), the filenames returned will also be of type bytes; in all other circumstances, they will be of type str.
      • This function can also support specifying a file descriptor; the file descriptor must refer to a directory.
      • Note
      • To encode str filenames to bytes, use fsencode().
      • See also
      • The scandir() function returns directory entries along with file attribute information, giving better performance for many common use cases.
      • Changed in version 3.2: The path parameter became optional.
      • New in version 3.3: Added support for specifying an open file descriptor for path.
      • Changed in version 3.6: Accepts a path-like object.
    • os.path.isdir(path)
      • Return True if path is an existing directory. This follows symbolic links, so both islink() and isdir() can be true for the same path.
      • Changed in version 3.6: Accepts a path-like object.
posted @ 2020-12-24 19:47  望星草  阅读(629)  评论(0编辑  收藏  举报