python基础之文件操作
文件操作有很多种
我们在这里可以大体分一下,文件的操作其实可以分为对文件整体的操作(创建文件,删除文件,重命名文件,获取文件属性)以及对文件内容的操作(修改文件内容)
先来看对文件整体的操作:
我们按照增删查改的顺序进行讲述
1 增
所谓增,即新建。
新建一个文件
f=open('lalal','w+') #如果该文件(lalal)不存在则创建,若存在则打开。open函数会返回一个文件描述符
新建一个目录:
>>> os.listdir() ['log', 'test1'] >>> os.mkdir('bin') >>> os.listdir() ['log', 'bin', 'test1']
2 删
所谓删,也就是删除。
删除文件:
>>> import os >>> os.listdir() ['log', 'test', 'bin', 'test1'] >>> os.remove('test') #仅仅只能删除文件,如果删除目录的话会报错。 >>> os.listdir() ['log', 'bin', 'test1']
删除目录:
>>> os.rmdir('bin') >>> os.listdir() ['log', 'test1']
3 查
查看文件的各种属性,如:目录下包含的文件,创建时间 修改时间 访问时间 文件权限 文件大小……
查看目录下包含的文件以及目录:
>>> os.listdir() ['log', 'bin', 'test1']
获取文件/目录信息:
>>> os.stat('test1') os.stat_result(st_mode=33188, st_ino=137156, st_dev=2050, st_nlink=1, st_uid=0, st_gid=0, st_size=0, st_atime=1463225144, st_mtime=1463225144, st_ctime=1463225144)
4 改
修改文件/目录的权限:
>>> os.stat('test1') os.stat_result(st_mode=33188, st_ino=137156, st_dev=2050, st_nlink=1, st_uid=0, st_gid=0, st_size=0, st_atime=1463225144, st_mtime=1463225144, st_ctime=1463225144) >>> os.chmod('test1',3) >>> os.stat('test1') os.stat_result(st_mode=32771, st_ino=137156, st_dev=2050, st_nlink=1, st_uid=0, st_gid=0, st_size=0, st_atime=1463225144, st_mtime=1463225144, st_ctime=1463225965) [root@slyoyo python_test]# lsa total 16 drwxr-xr-x. 4 root root 4096 May 14 04:31 . dr-xr-x---. 5 root root 4096 May 14 04:25 .. drwxr-xr-x. 2 root root 4096 May 14 04:31 bin drwxr-xr-x. 2 root root 4096 May 14 04:25 log -rw-r--r--. 1 root root 0 May 14 04:25 test1 [root@slyoyo python_test]# lsa total 16 drwxr-xr-x. 4 root root 4096 May 14 04:31 . dr-xr-x---. 5 root root 4096 May 14 04:25 .. drwxr-xr-x. 2 root root 4096 May 14 04:31 bin drwxr-xr-x. 2 root root 4096 May 14 04:25 log --------wx. 1 root root 0 May 14 04:25 test1
修改文件内容(读写文件)
读写文件前,我们先必须了解一下,在磁盘上读写文件的功能都是由操作系统提供的,现代操作系统不允许普通的程序直接操作磁盘,所以,读写文件就是请求操作 系统打开一个文件对象(通常称为文件描述符),然后,通过操作系统提供的接口从这个文件对象中读取数据(读文件),或者把数据写入这个文件对象(写文件)。
我们知道文件对象就是一个类,我们先来看一看python是如何实现这个类的。
class _IOBase(object): """ The abstract base class for all I/O classes, acting on streams of bytes. There is no public constructor. 是所有I/O类的基类,工作于字节流 This class provides dummy implementations for many methods that derived classes can override selectively; the default implementations represent a file that cannot be read, written or seeked. Even though IOBase does not declare read, readinto, or write because their signatures will vary, implementations and clients should consider those methods part of the interface. Also, implementations may raise UnsupportedOperation when operations they do not support are called. The basic type used for binary data read from or written to a file is bytes. bytearrays are accepted too, and in some cases (such as readinto) needed. Text I/O classes work with str data. Note that calling any method (except additional calls to close(), which are ignored) on a closed stream should raise a ValueError. IOBase (and its subclasses) support the iterator protocol, meaning that an IOBase object can be iterated over yielding the lines in a stream. IOBase also supports the :keyword:`with` statement. In this example, fp is closed after the suite of the with statement is complete: with open('spam.txt', 'r') as fp: fp.write('Spam and eggs!') """ def close(self, *args, **kwargs): # real signature unknown """ Flush and close the IO object. flush(刷写到磁盘)并关闭I/O对象 This method has no effect if the file is already closed. """ pass def fileno(self, *args, **kwargs): # real signature unknown """ Returns underlying file descriptor if one exists. 返回一个文件描述符 An IOError is raised if the IO object does not use a file descriptor. """ pass def flush(self, *args, **kwargs): # real signature unknown """ Flush write buffers, if applicable. 刷写到磁盘 This is not implemented for read-only and non-blocking streams. """ pass def isatty(self, *args, **kwargs): # real signature unknown """ Return whether this is an 'interactive' stream. Return False if it can't be determined. """ pass def readable(self, *args, **kwargs): # real signature unknown """ Return whether object was opened for reading. If False, read() will raise UnsupportedOperation. """ pass def readline(self, *args, **kwargs): # real signature unknown """ Read and return a line from the stream. 读一行 If limit is specified, at most limit bytes will be read. The line terminator is always b' ' for binary files; for text files, the newlines argument to open can be used to select the line terminator(s) recognized. """ pass def readlines(self, *args, **kwargs): # real signature unknown """ Return a list of lines from the stream. 将每行读出,形成一个列表并返回 hint can be specified to control the number of lines read: no more lines will be read if the total size (in bytes/characters) of all lines so far exceeds hint. """ pass def seek(self, *args, **kwargs): # real signature unknown """ Change stream position. 修改指针位置 Change the stream position to the given byte offset. The offset is interpreted relative to the position indicated by whence. Values for whence are: * 0 -- start of stream (the default); offset should be zero or positive * 1 -- current stream position; offset may be negative * 2 -- end of stream; offset is usually negative Return the new absolute position. """ pass def seekable(self, *args, **kwargs): # real signature unknown """ Return whether object supports random access. If False, seek(), tell() and truncate() will raise UnsupportedOperation. This method may need to do a test seek(). """ pass def tell(self, *args, **kwargs): # real signature unknown """ Return current stream position. 返回当前指针位置""" pass def truncate(self, *args, **kwargs): # real signature unknown """ Truncate file to size bytes. 截取当前文件描述符的指针之前的内容 File pointer is left unchanged. Size defaults to the current IO position as reported by tell(). Returns the new size. """ pass def writable(self, *args, **kwargs): # real signature unknown """ Return whether object was opened for writing. If False, write() will raise UnsupportedOperation. """ pass def writelines(self, *args, **kwargs): # real signature unknown pass def _checkClosed(self, *args, **kwargs): # real signature unknown pass def _checkReadable(self, *args, **kwargs): # real signature unknown pass def _checkSeekable(self, *args, **kwargs): # real signature unknown pass def _checkWritable(self, *args, **kwargs): # real signature unknown pass def __del__(self, *args, **kwargs): # real signature unknown """ """ pass def __enter__(self, *args, **kwargs): # real signature unknown pass def __exit__(self, *args, **kwargs): # real signature unknown pass def __init__(self, *args, **kwargs): # real signature unknown pass def __iter__(self, *args, **kwargs): # real signature unknown """ Implement iter(self). """ 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 closed = property(lambda self: object(), lambda self, v: None, lambda self: None) # default __dict__ = None # (!) real value is ''