博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python 文件目录操作
阅读量:4228 次
发布时间:2019-05-26

本文共 12080 字,大约阅读时间需要 40 分钟。

File 操作

file.close()

# test.pyfile = open("runoob.txt", "wb")print("file name: ", file.name)file.close()
[root@master python3_learning]# python3 test.pyfile name:  runoob.txt

file.flush()

flush() 方法是用来刷新缓冲区的,即将缓冲区中的数据立刻写入文件,同时清空缓冲区,不需要是被动的等待输出缓冲区写入。

一般情况下,文件关闭后会自动刷新缓冲区,但有时你需要在关闭前刷新它,这时就可以使用 flush() 方法。

file.fileno()

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

file.isatty()

# test.pyfile = open("runoob.txt", "wb")print('is a tty? :', file.isatty())file.close()
[root@master python3_learning]# python3 test.pyis a tty? : False

file.read()

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

file.readline()

# 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

file.readlines()

# 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']

file.seek()

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'

file.tell()

# 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

file.truncate()

# 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

file.write()

# 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']

file.writelines()

# 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 操作

直不太明白为什么像 os.getcwd() 、os.listdir() 和 os.chdir() 这些路径操作不是在 os.path 模块下,难道是什么遗留问题?

os.access()

# 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

os.chdir()

# 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

os.chflags()

  • path -- 文件名路径或目录路径。

  • flags -- 可以是以下值:

    • stat.UF_NODUMP: 非转储文件
    • stat.UF_IMMUTABLE: 文件是只读的
    • stat.UF_APPEND: 文件只能追加内容
    • stat.UF_NOUNLINK: 文件不可删除
    • stat.UF_OPAQUE: 目录不透明,需要通过联合堆栈查看
    • stat.SF_ARCHIVED: 可存档文件(超级用户可设)
    • stat.SF_IMMUTABLE: 文件是只读的(超级用户可设)
    • stat.SF_APPEND: 文件只能追加内容(超级用户可设)
    • stat.SF_NOUNLINK: 文件不可删除(超级用户可设)
    • stat.SF_SNAPSHOT: 快照文件(超级用户可设)
# test.pyimport osimport statpath = '/tmp/test.txt'os.chflags(path, stat.SF_NOUNLINK)

os.chmod()

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()

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()

os.chroot() 方法用于更改当前进程的根目录为指定的目录,使用该函数需要管理员权限。

# test.pyimport osos.chroot('/tmp')

os.close()

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()

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()

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()

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()

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()

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()

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()

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()

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)

os.getcwd()

>>> import os>>> os.getcwd()'/root/workspace/python3_learning'

os.link(path, dst)

>>> import os>>> os.link('test.txt', 'test2.txt')

os.listdir()

>>> 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()

os.makedirs() 方法用于递归创建目录。如果子目录创建失败或者已经存在,会抛出一个 OSError 的异常。

>>> path = "/tmp/home/monthly/daily">>> os.makedirs(path, 0o777)

os.makedir()

os.mkdir() 方法用于以数字权限模式创建目录。默认的模式为 0777 (八进制)。

>>> path = "/tmp/home/monthly/daily/hourly">>> os.mkdir(path, 0755)

os.readlink()

os.readlink() 方法用于返回软链接所指向的文件,可能返回绝对或相对路径。

>>> import os>>> src = '/usr/bin/python'>>> dst = '/tmp/python'>>> os.symlink(src, dst)>>> os.readlink(dst)'/usr/bin/python'

os.remove()

os.remove() 方法用于删除指定路径的文件。如果指定的路径是一个目录,将抛出OSError。

>>> import os>>> os.remove('test2.txt')

os.removedirs()

os.removedirs() 方法用于递归删除目录 

>>> import os>>> os.remove('/test')

os.rename()

>>> import os>>> os.rename('src', 'dst')

os.renames()

os.renames() 方法用于递归重命名目录或文件。类似rename()。

os.renames(old, new)

  • old -- 要重命名的目录

  • new --文件或目录的新名字。甚至可以是包含在目录中的文件,或者完整的目录树。

>>> import os>>> os.rename('old', 'dst')

os.rmdir()

os.rmdir() 方法用于删除指定路径的目录。仅当这文件夹是空的才可以, 否则, 抛出OSError。

>>> import os>>> os.redir('test')

os.stat()

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)

os.symlink()

>>> import os>>> os.symlink('src', 'dst')

os.unlink()

os.unlink() 方法用于删除文件,如果文件是一个目录则返回一个错误。

>>> import os>>> os.unlink('test.txt')

os.utime()

os.utime(path, times)
  • path -- 文件路径

  • times -- 如果时间是 None, 则文件的访问和修改设为当前时间 。 否则, 时间是一个 2-tuple数字, (atime, mtime) 用来分别作为访问和修改的时间。

>>> import os>>> os.utime('foo.txt', (1330712280, 1330712292))

os.pardir()

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()

怎么遍历一个目录及其子目录下的所有文件?不要再傻傻的自己去写递归函数啦!

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/

你可能感兴趣的文章
StackOverFlow异常记录
查看>>
SpringMvc4.1:注解JsonView与泛型返回类
查看>>
SpringMVC+Mybatis+事务回滚+异常封装返回
查看>>
简单的MFC窗口程序的创建、使用命令行工具cl.exe,linker.exe等编译连接
查看>>
计算机网络实验报告(三):Cisco Packet Tracer 实验
查看>>
嵌入式系统基础学习笔记(九):基于 SPI 协议在 0.96 寸 OLED上【平滑显示汉字】及【温湿度数据采集显示】
查看>>
嵌入式系统基础学习笔记(十):
查看>>
网络通信编程学习笔记(七):Java与MQTT
查看>>
人工智能与机器学习学习笔记(二)
查看>>
Peer-to-Peer with VB .NET
查看>>
Java Database Programming Bible
查看>>
Model Driven Architecture: Applying MDA to Enterprise Computing
查看>>
Pro Jakarta Commons
查看>>
Pro JSP, Third Edition
查看>>
LightWave 3D 8 Revealed
查看>>
The Cg Tutorial: The Definitive Guide to Programmable Real-Time Graphics
查看>>
Operating Systems Design and Implementation (3rd Edition)
查看>>
Beginning Visual C# 2005
查看>>
Professional C# 2005
查看>>
Faster Smarter Beginning Programming
查看>>