本文共 12080 字,大约阅读时间需要 40 分钟。
# test.pyfile = open("runoob.txt", "wb")print("file name: ", file.name)file.close()
[root@master python3_learning]# python3 test.pyfile name: runoob.txt
flush() 方法是用来刷新缓冲区的,即将缓冲区中的数据立刻写入文件,同时清空缓冲区,不需要是被动的等待输出缓冲区写入。
一般情况下,文件关闭后会自动刷新缓冲区,但有时你需要在关闭前刷新它,这时就可以使用 flush() 方法。
fileno() 方法返回一个整型的文件描述符(file descriptor FD 整型),可用于底层操作系统的 I/O 操作。
# test.pyfile = open("runoob.txt", "wb")print("file name: ", file.name)fid = file.fileno()print("file descriptor: ", fid)file.close()
[root@master python3_learning]# python3 test.pyfile name: runoob.txtfile descriptor: 3
# test.pyfile = open("runoob.txt", "wb")print('is a tty? :', file.isatty())file.close()
[root@master python3_learning]# python3 test.pyis a tty? : False
read() 方法用于从文件读取指定的字节数,如果未给定或为负则读取所有。
# runoob.txtfirst linesecond linethird line
# test.pyfile = open("runoob.txt", "r+")print("file name: ", file.name)line = file.read(10)print("the string of reading: %s" % (line))line = file.read()print("the string of reading: %s" % (line))file.close()
[root@master python3_learning]# python3 test.pyfile name: runoob.txtthe string of reading: first linethe string of reading: second linethird line
# runoob.txtfirst linesecond linethird line
# test.pyfile = open("runoob.txt", "r+")print("file name: ", file.name)line = file.readline()print("the first line of reading: %s" % (line))line = file.readline(5)print("the string of reading: %s" % (line))file.close()
[root@master python3_learning]# python3 test.pyfile name: runoob.txtthe first line of reading: first linethe string of reading: secon
# runoob.txtfirst linesecond linethird line
# test.pyfile = open("runoob.txt", "r+")print("file name: ", file.name)line = file.readlines()print("the result of reading: %s" % (line))file.close()
[root@master python3_learning]# python3 test.pyfile name: runoob.txtthe result of reading: ['first line\n', 'second line\n', 'third line\n']
fileObject.seek(offset[, whence])
offset -- 开始的偏移量,也就是代表需要移动偏移的字节数,如果是负数表示从倒数第几位开始。
whence:可选,默认值为 0。给 offset 定义一个参数,表示要从哪个位置开始偏移;0 代表从文件开头开始算起,1 代表从当前位置开始算起,2 代表从文件末尾算起。
# test.pyf = open("workfile", "rb+")f.write(b'0123456789abcdef')print(f.seek(5))print(f.read(2))print(f.seek(-3, 2))print(f.read(1))
[root@master python3_learning]# python3 test.py5b'56'13b'd'
# runoob.txtfirst linesecond linethird line
# test.pyfile = open("runoob.txt", "r+")print("file name: ", file.name)pos=file.tell()print('current position:%d' % (pos))line = file.readline()print("the result of reading: %s" % (line))pos=file.tell()print('current position:%d' % (pos))file.close()
[root@master python3_learning]# python3 test.pyfile name: runoob.txtcurrent position:0the result of reading: first linecurrent position:11
# runoob.txtfirst linesecond linethird line
# test.pyfile = open("runoob.txt", "r+")print("file name: ", file.name)file.truncate(8)line = file.read()print('the result of reading:%s' % (line))file.close()
[root@master python3_learning]# python3 test.pyfile name: runoob.txtthe result of reading:first li
# runoob.txtfirst linesecond linethird line
# test.pyfile = open("runoob.txt", "r+")print("file name: ", file.name)# write a new line after the file endfile.seek(0, 2)line = file.write('hello world')file.seek(0, 0)line = file.readlines()print('the result of reading:%s' % (line))file.close()
[root@master python3_learning]# python3 test.pyfile name: runoob.txtthe result of reading:['first line\n', 'second line\n', 'third line\n', 'hello world']
# test.pyfile = open("runoob.txt", "w")print("file name: ", file.name)seq = ['hello\n', 'world\n']file.writelines(seq)file.close()
[root@master python3_learning]# python3 test.pyfile name: runoob.txt
# runoob.txthelloworld
一直不太明白为什么像 os.getcwd() 、os.listdir() 和 os.chdir() 这些路径操作不是在 os.path 模块下,难道是什么遗留问题?
# test.txthello worldnice to meet you
# test.pyimport osret = os.access('test.txt', os.F_OK)print('file exists? : %s' % ret)ret = os.access('test.txt', os.R_OK)print('file readable? : %s' % ret)ret = os.access('test.txt', os.W_OK)print('file writable? : %s' % ret)ret = os.access('test.txt', os.X_OK)print('file executable? : %s' % ret)
[root@master python3_learning]# python3 test.pyfile exists? : Truefile readable? : Truefile writable? : Truefile executable? : False
# test.pyimport ospath = '/tmp'ret = os.getcwd()print('current work directory: %s' % ret)os.chdir(path)ret = os.getcwd()print('current work directory: %s' % ret)
[root@master python3_learning]# python3 test.py current work directory: /root/workspace/python3_learningcurrent work directory: /tmp
path -- 文件名路径或目录路径。
flags -- 可以是以下值:
# test.pyimport osimport statpath = '/tmp/test.txt'os.chflags(path, stat.SF_NOUNLINK)
os.chmod() 方法用于更改文件或目录的权限。
# test.pyimport osimport stat# R -> readable # W -> writable # X -> executable # USR -> user# GRP -> group# OTH -> other# user group can execute fileos.chmod('/tmp/test.txt', stat.S_IXGRP)# other can write fileos.chmod('/tmp/test.txt', stat.S_IWOTH)
os.chown() 方法用于更改文件所有者,如果不修改可以设置为 -1, 你需要超级用户权限来执行权限修改操作。
# test.pyimport osos.chown('test.txt', 1001, -1)
[root@master python3_learning]# ll test.txt-rw-r--r--. 1 root root 29 Dec 3 15:48 test.txt[root@master python3_learning]# python3 test.py[root@master python3_learning]# ll test.txt-rw-r--r--. 1 looking root 29 Dec 3 15:48 test.txt
os.chroot() 方法用于更改当前进程的根目录为指定的目录,使用该函数需要管理员权限。
# test.pyimport osos.chroot('/tmp')
os.close() 方法用于关闭指定的文件描述符 fd。
# test.pyimport osfd = os.open('test.txt', os.O_RDWR|os.O_CREAT)os.write(fd, "This is test".encode('utf-8'))os.close(fd)
os.closerange() 方法用于关闭所有文件描述符 fd,从 fd_low (包含) 到 fd_high (不包含), 错误会忽略。
该方法类似于:
for fd in xrange(fd_low, fd_high): try: os.close(fd) except OSError: pass
# test.pyimport osfd = os.open('test.txt', os.O_RDWR|os.O_CREAT)os.write(fd, "This is test".encode('utf-8'))os.closerange(fd, fd)
os.dup() 方法用于复制文件描述符 fd。
# test.pyimport osfd = os.open('test.txt', os.O_RDWR|os.O_CREAT)d_fd = os.dup(fd)os.write(fd, "This is test".encode('utf-8'))os.close(fd)
os.dup2() 方法用于将一个文件描述符 fd 复制到另一个 fd2。
# test.pyimport osfd = open('test.txt', 'a')os.dup2(fd.fileno(), 1)fd.close()print('hello')print('world')
[root@master python3_learning]# cat test.txt[root@master python3_learning]# python3 test.py[root@master python3_learning]# cat test.txthelloworld
os.fchdir() 方法通过文件描述符改变当前工作目录。
# test.pyimport osprint('current work directory: %s' % os.getcwd())fd = os.open('/tmp', os.O_RDONLY)os.fchdir(fd)print('current work directory: %s' % os.getcwd())os.close(fd)
[root@master python3_learning]# python3 test.pycurrent work directory: /root/workspace/python3_learningcurrent work directory: /tmp
os.fchmod() 方法用于改变一个文件的访问权限,该文件由参数fd指定,参数mode是Unix下的文件访问权限。
# test.pyimport osfd = os.open('/tmp', os.O_RDONLY)os.fchmod(fd, stat.S_IXGRP)os.fchmod(fd, stat.S_IWOTH)os.close(fd)
os.fchown() 方法用于修改一个文件的所有权,这个函数修改一个文件的用户ID和用户组ID,该文件由文件描述符 fd 指定。
# test.pyimport osfd = os.open('/tmp', os.O_RDONLY)# set file user id 100os.fchown(fd, 100, -1)# set file group id 50os.fchown(fd, -1, 50)os.close(fd)
os.fdopen() 方法用于通过文件描述符 fd 创建一个文件对象,并返回这个文件对象。该方法是内置函数 的别名,可以接收一样的参数,唯一的区别是 fdopen() 的第一个参数必须是整型(文件描述符)。
# test.pyimport osfd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )fo = os.fdopen(fd, "w+")print ("Current I/O pointer position :%d" % fo.tell())fo.write( "Python is a great language.\nYeah its great!!\n");os.lseek(fd, 0, 0)str = os.read(fd, 100)print ("Read String is : ", str)print ("Current I/O pointer position :%d" % fo.tell())os.close( fd )
os.fstat() 方法用于返回文件描述符fd的状态,类似 stat()。
# test.pyimport os fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )info = os.fstat(fd)print('file info: ', info)os.close( fd )
[root@master python3_learning]# python3 test.pyfile info: os.stat_result(st_mode=33261, st_ino=50387509, st_dev=64768, st_nlink=1, st_uid=0, st_gid=0, st_size=12, st_atime=1611891943, st_mtime=1611891939, st_ctime=1611891939)
>>> import os>>> os.getcwd()'/root/workspace/python3_learning'
>>> import os>>> os.link('test.txt', 'test2.txt')
>>> import os>>> os.listdir('.')['world.py', 'ip-address.py', 'workfile', 'test.txt', 'my-testfile', 'minio_client.py', 'test2.py', 'test.py', 'runoob.txt', 'foo.txt', 'test2.txt']
os.makedirs() 方法用于递归创建目录。如果子目录创建失败或者已经存在,会抛出一个 OSError 的异常。
>>> path = "/tmp/home/monthly/daily">>> os.makedirs(path, 0o777)
os.mkdir() 方法用于以数字权限模式创建目录。默认的模式为 0777 (八进制)。
>>> path = "/tmp/home/monthly/daily/hourly">>> os.mkdir(path, 0755)
os.readlink() 方法用于返回软链接所指向的文件,可能返回绝对或相对路径。
>>> import os>>> src = '/usr/bin/python'>>> dst = '/tmp/python'>>> os.symlink(src, dst)>>> os.readlink(dst)'/usr/bin/python'
os.remove() 方法用于删除指定路径的文件。如果指定的路径是一个目录,将抛出OSError。
>>> import os>>> os.remove('test2.txt')
os.removedirs() 方法用于递归删除目录
>>> import os>>> os.remove('/test')
>>> import os>>> os.rename('src', 'dst')
os.renames() 方法用于递归重命名目录或文件。类似rename()。
os.renames(old, new)
old -- 要重命名的目录
new --文件或目录的新名字。甚至可以是包含在目录中的文件,或者完整的目录树。
>>> import os>>> os.rename('old', 'dst')
os.rmdir() 方法用于删除指定路径的目录。仅当这文件夹是空的才可以, 否则, 抛出OSError。
>>> import os>>> os.redir('test')
os.stat() 方法用于在给定的路径上执行一个系统 stat 的调用。
>>> import os>>> os.stat('foo.txt')os.stat_result(st_mode=33261, st_ino=50387509, st_dev=64768, st_nlink=1, st_uid=0, st_gid=0, st_size=12, st_atime=1611891943, st_mtime=1611891939, st_ctime=1611891939)
>>> import os>>> os.symlink('src', 'dst')
os.unlink() 方法用于删除文件,如果文件是一个目录则返回一个错误。
>>> import os>>> os.unlink('test.txt')
os.utime(path, times)
path -- 文件路径
times -- 如果时间是 None, 则文件的访问和修改设为当前时间 。 否则, 时间是一个 2-tuple数字, (atime, mtime) 用来分别作为访问和修改的时间。
>>> import os>>> os.utime('foo.txt', (1330712280, 1330712292))
os.pardir() 获取当前目录的父目录(上一级目录),以字符串形式显示目录名。
>>> import os>>> path = os.getcwd()>>> path'/root/workspace/python3_learning'>>> os.path.abspath(os.path.join(path, os.pardir))'/root/workspace'>>> os.path.abspath(os.pardir)'/root/workspace'
怎么遍历一个目录及其子目录下的所有文件?不要再傻傻的自己去写递归函数啦!
os.walk() 方法可以创建一个生成器,用以生成所要查找的目录及其子目录下的所有文件。一个简单易用的文件、目录遍历器,可以帮助我们高效的处理文件、目录方面的事情。
# test.pyimport osfor root, dirs, files in os.walk("/root/workspace/shell_learning", topdown=False): print(root, dirs, files) for file in files: print(os.path.join(root, file))
[root@master python3_learning]# python3 test.py/root/workspace/shell_learning/test1_dir [] ['out.txt']/root/workspace/shell_learning/test1_dir/out.txt/root/workspace/shell_learning/test2_dir/test1_dir [] ['out.txt']/root/workspace/shell_learning/test2_dir/test1_dir/out.txt/root/workspace/shell_learning/test2_dir ['test1_dir'] []/root/workspace/shell_learning ['test1_dir', 'test2_dir'] ['passwd.txt', 'user.txt', 'get-docker.sh', 'textfile.txt', 'file1.txt', 'file2.txt', 'test.rb', 'textfile.txt.link', 'textfile2.txt', 'out.txt', 'test.txt', 'file3.txt', 'out.txt.link', 'test.sh']/root/workspace/shell_learning/passwd.txt/root/workspace/shell_learning/user.txt/root/workspace/shell_learning/get-docker.sh/root/workspace/shell_learning/textfile.txt/root/workspace/shell_learning/file1.txt/root/workspace/shell_learning/file2.txt/root/workspace/shell_learning/test.rb/root/workspace/shell_learning/textfile.txt.link/root/workspace/shell_learning/textfile2.txt/root/workspace/shell_learning/out.txt/root/workspace/shell_learning/test.txt/root/workspace/shell_learning/file3.txt/root/workspace/shell_learning/out.txt.link/root/workspace/shell_learning/test.sh
转载地址:http://bijqi.baihongyu.com/