关于文件操作请参考:https://www.cnblogs.com/wj-1314/p/8476315.html

一:os模块

os模块提供了许多允许你程序与操作系统直接交互的功能

  1. os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径
  2.  
  3. os.chdir("dirname") 改变当前脚本工作目录;相当于shellcd
  4.  
  5. os.curdir 返回当前目录: ('.')
  6.  
  7. os.pardir 获取当前目录的父目录字符串名:('..')
  8.  
  9. os.makedirs('dirname1/dirname2') 可生成多层递归目录
  10.  
  11. os.removedirs('dirname1') 若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
  12.  
  13. os.mkdir('dirname') 生成单级目录;相当于shellmkdir dirname
  14.  
  15. os.rmdir('dirname') 删除单级空目录,若目录不为空则无法删除,报错;相当于shellrmdir dirname
  16.  
  17. os.listdir('dirname') 列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
  18.  
  19. os.remove() 删除一个文件
  20.  
  21. os.rename("oldname","newname") 重命名文件/目录
  22.  
  23. os.stat('path/filename') 获取文件/目录信息
  24.  
  25. os.sep 输出操作系统特定的路径分隔符,win下为"\\",Linux下为"/"
  26.  
  27. os.linesep 输出当前平台使用的行终止符,win下为"\t\n",Linux下为"\n"
  28.  
  29. os.pathsep 输出用于分割文件路径的字符串 win下为;,Linux下为:
  30.  
  31. os.name 输出字符串指示当前使用平台。win->'nt'; Linux->'posix'
  32.  
  33. os.system("bash command") 运行shell命令,直接显示
  34.  
  35. os.environ 获取系统环境变量
  36.  
  37. os.path.abspath(path) 返回path规范化的绝对路径
  38.  
  39. os.path.split(path) path分割成目录和文件名二元组返回
  40.  
  41. os.path.dirname(path) 返回path的目录。其实就是os.path.split(path)的第一个元素
  42.  
  43. os.path.basename(path) 返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即 os.path.split(path)的第二个元素
  44.  
  45. os.path.exists(path) 如果path存在,返回True;如果path不存在,返回False
  46.  
  47. os.path.isabs(path) 如果path是绝对路径,返回True
  48.  
  49. os.path.isfile(path) 如果path是一个存在的文件,返回True。否则返回False
  50.  
  51. os.path.isdir(path) 如果path是一个存在的目录,则返回True。否则返回False
  52.  
  53. os.path.join(path1[, path2[, ...]]) 将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
  54.  
  55. os.path.getatime(path) 返回path所指向的文件或者目录的最后存取时间
  56.  
  57. os.path.getmtime(path) 返回path所指向的文件或者目录的最后修改时间

  

1,当前路径及路径下的文件

  • os.getcwd():查看当前所在路径。
  • os.listdir(path):列举目录下的所有文件。返回的是列表类型。
  1. >>> import os
  2. >>> os.getcwd()
  3. 'D:\\pythontest\\ostest'
  4. >>> os.listdir(os.getcwd())
  5. ['hello.py', 'test.txt']

  

2,绝对路径

  • os.path.abspath(path):返回path的绝对路径。
  1. >>> os.path.abspath('.')
  2. 'D:\\pythontest\\ostest'
  3. >>> os.path.abspath('..')
  4. 'D:\\pythontest'

  

3,查看路径的文件夹部分和文件名部分

  • os.path.split(path):将路径分解为(文件夹,文件名),返回的是元组类型。可以看出,若路径字符串最后一个字符是\,则只有文件夹部分有值;若路径字符串中均无\,则只有文件名部分有值。若路径字符串有\,且不在最后,则文件夹和文件名均有值。且返回的文件夹的结果不包含\.
  • os.path.join(path1,path2,...):将path进行组合,若其中有绝对路径,则之前的path将被删除。
  1. >>> os.path.split('D:\\pythontest\\ostest\\Hello.py')
  2. ('D:\\pythontest\\ostest', 'Hello.py')
  3. >>> os.path.split('.')
  4. ('', '.')
  5. >>> os.path.split('D:\\pythontest\\ostest\\')
  6. ('D:\\pythontest\\ostest', '')
  7. >>> os.path.split('D:\\pythontest\\ostest')
  8. ('D:\\pythontest', 'ostest')
  9. >>> os.path.join('D:\\pythontest', 'ostest')
  10. 'D:\\pythontest\\ostest'
  11. >>> os.path.join('D:\\pythontest\\ostest', 'hello.py')
  12. 'D:\\pythontest\\ostest\\hello.py'
  13. >>> os.path.join('D:\\pythontest\\b', 'D:\\pythontest\\a')
  14. 'D:\\pythontest\\a'
  • os.path.dirname(path):返回path中的文件夹部分,结果不包含'\'
  1. >>> os.path.dirname('D:\\pythontest\\ostest\\hello.py')
  2. 'D:\\pythontest\\ostest'
  3. >>> os.path.dirname('.')
  4. ''
  5. >>> os.path.dirname('D:\\pythontest\\ostest\\')
  6. 'D:\\pythontest\\ostest'
  7. >>> os.path.dirname('D:\\pythontest\\ostest')
  8. 'D:\\pythontest'
  • os.path.basename(path):返回path中的文件名。
  1. >>> os.path.basename('D:\\pythontest\\ostest\\hello.py')
  2. 'hello.py'
  3. >>> os.path.basename('.')
  4. '.'
  5. >>> os.path.basename('D:\\pythontest\\ostest\\')
  6. ''
  7. >>> os.path.basename('D:\\pythontest\\ostest')
  8. 'ostest'

  

4,查看文件时间

  • os.path.getmtime(path):文件或文件夹的最后修改时间,从新纪元到访问时的秒数。
  • os.path.getatime(path):文件或文件夹的最后访问时间,从新纪元到访问时的秒数。
  • os.path.getctime(path):文件或文件夹的创建时间,从新纪元到访问时的秒数。
  1. >>> os.path.getmtime('D:\\pythontest\\ostest\\hello.py')
  2. 1481695651.857048
  3. >>> os.path.getatime('D:\\pythontest\\ostest\\hello.py')
  4. 1481687717.8506615
  5. >>> os.path.getctime('D:\\pythontest\\ostest\\hello.py')
  6. 1481687717.8506615

  

5,查看文件大小

  • os.path.getsize(path):文件或文件夹的大小,若是文件夹返回0。
  1. >>> os.path.getsize('D:\\pythontest\\ostest\\hello.py')
  2. 58L
  3. >>> os.path.getsize('D:\\pythontest\\ostest')
  4. 0L

  

6,查看文件是否存在

  • os.path.exists(path):文件或文件夹是否存在,返回True 或 False。
  1. >>> os.listdir(os.getcwd())
  2. ['hello.py', 'test.txt']
  3. >>> os.path.exists('D:\\pythontest\\ostest\\hello.py')
  4. True
  5. >>> os.path.exists('D:\\pythontest\\ostest\\Hello.py')
  6. True
  7. >>> os.path.exists('D:\\pythontest\\ostest\\Hello1.py')
  8. False

  

7,一些表现形式参数

  • os中定义了一组文件、路径在不同操作系统中的表现形式参数,如:
  1. >>> os.sep
  2. '\\'
  3. >>> os.extsep
  4. '.'
  5. >>> os.pathsep
  6. ';'
  7. >>> os.linesep
  8. '\r\n'

  

8 在读文件的时候往往需要遍历文件夹,下面写一下遍历文件夹操作的方法

  1. import os
  2.  
  3. txt_rootdir = 'txt_result'
  4.  
  5. filename_list = os.listdir(txt_rootdir)
  6.  
  7. for i in range(0,len(filename_list)):
  8. file_path = os.path.join(txt_rootdir,filename_list[i])
  9. if os.path.isfile(file_path):
  10. print("ok running")
  11. # 删除一个文件
  12. # os.remove()

  

9,os.listdir和os.walk获得文件路径的区别

  参考文献:https://www.cnblogs.com/jiaxin359/p/7324077.html

  情况一:在一个目录下面只有文件,没有文件夹的时候,这个时候可以使用os.listdir

  情况二:在递归的情况,一个目录下面既有目录也有文件,使用os.walk

9.1 情况1详解

  在我们的桌面上有一个file目录(文件夹),里面有三个文件,如下:

  用下面的程序获得文件的绝对路径:

  1. import os
  2.  
  3. path = r'C:\Users\Administrator\Desktop\file'
  4. for filename in os.listdir(path):
  5. print(os.path.join(path,filename))

  使用os.listdir读取到一个目录下面所有的文件,然后使用os.path.join 把目录和路径和文件结合起来,就得到了文件的绝对路径,结果如下:

  1. C:\Users\Administrator\Desktop\file\test1.txt
  2. C:\Users\Administrator\Desktop\file\test2.txt
  3. C:\Users\Administrator\Desktop\file\test3.txt

  

9.2 情况2详解

  我们首先在桌面上建立一个file目录,里面的组织结构如下:

  运行一下代码:

  1. import os
  2.  
  3. path = r'C:\Users\Administrator\Desktop\file'
  4. for dirpath,dirnames,filenames in os.walk(path):
  5. print(dirpath,dirnames,filenames)

  输出结果如下:

  1. C:\Users\Administrator\Desktop\file ['file1', 'file2'] ['file_test1.txt', 'file_test2 .txt']
  2. C:\Users\Administrator\Desktop\file\file1 [] ['file1_test1.txt', 'file1_test2.txt']
  3. C:\Users\Administrator\Desktop\file\file2 [] ['file2_test1.txt']

  

  os.walk输入一个路径名称,以yield的方式(其实是一个生成器)返回一个三元组 dirpath, dirnames, filenames,

  dirpath为目录的路径,为一个字符串。比如上面的 C:\Users\Administrator\Desktop\fileC:\Users\Administrator\Desktop\file\file1等。

  dirnames列出了目录路径下面所有存在的目录的名称。比如在 C:\Users\Administrator\Desktop\file下面有两个目录:file1和file2,那么它就列出了这个目录路径下的目录名称。

  filenames列出了目录路径下面所有文件的名称。同样在 C:\Users\Administrator\Desktop\file下面有两个文件file_test1.txt和file_test2 .txt,那么程序将会列出这两个文件名。

  如何获得一个路径下面所有的文件路径:

  1. import os
  2. path = r'C:\Users\Administrator\Desktop\file'
  3. for dirpath,dirnames,filenames in os.walk(path):
  4. for filename in filenames:
  5. print(os.path.join(dirpath,filename))

  得到的结果如下:

  1. C:\Users\Administrator\Desktop\file\file_test1.txt
  2. C:\Users\Administrator\Desktop\file\file_test2 .txt
  3. C:\Users\Administrator\Desktop\file\file1\file1_test1.txt
  4. C:\Users\Administrator\Desktop\file\file1\file1_test2.txt
  5. C:\Users\Administrator\Desktop\file\file2\file2_test1.txt

  

二,sys模块

  1. sys.argv 命令行参数List,第一个元素是程序本身路径
  2. sys.exit(n) 退出程序,正常退出时exit(0)
  3. sys.version 获取Python解释程序的版本信息
  4. sys.maxint 最大的Int
  5. sys.path 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
  6. sys.platform 返回操作系统平台名称
  7. sys.stdout.write('please:') #标准输出 , 引出进度条的例子, 注,在py3上不行,可以用print代替
  8. val = sys.stdin.readline()[:-1] #标准输入
  9. sys.getrecursionlimit() #获取最大递归层数
  10. sys.setrecursionlimit(1200) #设置最大递归层数
  11. sys.getdefaultencoding() #获取解释器默认编码
  12. sys.getfilesystemencoding #获取内存数据存到文件里的默认编码

1,sys.path :返回模块的搜索路径,初始化使用pythonpath环境变量的值

  sys.path.append("自定义模块路径)

  1. >>> import os
  2. >>> import sys
  3. >>> sys.path
  4. ['', 'D:\\python3\\python36.zip', 'D:\\python3\\DLLs', 'D:\\python3\\lib', 'D:\\python3', 'D:\\python3\\lib\\site-packages', 'D:\\python3\\lib\\site-packages\\win32', 'D:\\python3\\lib\\site-packages\\win32\\lib', 'D:\\python3\\lib\\site-packages\\Pythonwin']
  5. >>>

2,进度条:

  1. #=========知识储备==========
  2. #进度条的效果
  3. [# ]
  4. [## ]
  5. [### ]
  6. [#### ]
  7.  
  8. #指定宽度
  9. print('[%-15s]' %'#')
  10. print('[%-15s]' %'##')
  11. print('[%-15s]' %'###')
  12. print('[%-15s]' %'####')
  13.  
  14. #打印%
  15. print('%s%%' %(100)) #第二个%号代表取消第一个%的特殊意义
  16.  
  17. #可传参来控制宽度
  18. print('[%%-%ds]' %50) #[%-50s]
  19. print(('[%%-%ds]' %50) %'#')
  20. print(('[%%-%ds]' %50) %'##')
  21. print(('[%%-%ds]' %50) %'###')
  22.  
  23. #=========实现打印进度条函数==========
  24. import sys
  25. import time
  26.  
  27. def progress(percent,width=50):
  28. if percent >= 1:
  29. percent=1
  30. show_str=('[%%-%ds]' %width) %(int(width*percent)*'#')
  31. print('\r%s %d%%' %(show_str,int(100*percent)),file=sys.stdout,flush=True,end='')
  32.  
  33. #=========应用==========
  34. data_size=1025
  35. recv_size=0
  36. while recv_size < data_size:
  37. time.sleep(0.1) #模拟数据的传输延迟
  38. recv_size+=1024 #每次收1024
  39.  
  40. percent=recv_size/data_size #接收的比例
  41. progress(percent,width=70) #进度条的宽度70
  42.  
  43. 打印进度条

3,练习

  1. import sys
  2.  
  3. sys.platform
  4. 'win32'
  5.  
  6. sys.stdout
  7. <_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>
  8.  
  9. sys.argv
  10. ['D:\\pycharm专业版\\PyCharm 2017.1.4\\helpers\\pydev\\pydevconsole.py', '49701', '49702']
  11.  
  12. sys.version
  13. '3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)]'
  14.  
  15. sys.stdin.readline()
  16. 'the line is write'
  17. "'the line is write'\n"

  

三,shutil模块

高级的 文件、文件夹、压缩包 处理模块

shutil.copyfileobj(fsrc, fdst[, length])
将文件内容拷贝到另一个文件中

  1. import shutil
  2. shutil.copyfileobj(open('old.xml','r'), open('new.xml', 'w'))

  

shutil.copyfile(src, dst)
拷贝文件

  1. shutil.copyfile('f1.log', 'f2.log') #目标文件无需存在

  

shutil.copymode(src, dst)
仅拷贝权限。内容、组、用户均不变

  1. shutil.copymode('f1.log', 'f2.log') #目标文件必须存在

  

shutil.copystat(src, dst)
仅拷贝状态的信息,包括:mode bits, atime, mtime, flags

  1. shutil.copystat('f1.log', 'f2.log') #目标文件必须存在

  

shutil.copy(src, dst)
拷贝文件和权限

  1. import shutil
  2. shutil.copy('f1.log', 'f2.log')

  

shutil.copy2(src, dst)
拷贝文件和状态信息

  1. import shutil
  2. shutil.copy2('f1.log', 'f2.log')

  

shutil.ignore_patterns(*patterns)
shutil.copytree(src, dst, symlinks=False, ignore=None)
递归的去拷贝文件夹

  1. import shutil
  2. shutil.copytree('folder1', 'folder2', ignore=shutil.ignore_patterns('*.pyc', 'tmp*'))
  3. #目标目录不能存在,注意对folder2目录父级目录要有可写权限,ignore的意思是排除

  

shutil.rmtree(path[, ignore_errors[, onerror]])
递归的去删除文件

  1. import shutil
  2. shutil.rmtree('folder1')

  

shutil.move(src, dst)
递归的去移动文件,它类似mv命令,其实就是重命名。

  1. import shutil
  2. shutil.move('folder1', 'folder3')

  

shutil.make_archive(base_name, format,...)
创建压缩包并返回文件路径,例如:zip、tar
创建压缩包并返回文件路径,例如:zip、tar

  • base_name: 压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径,

如 data_bak =>保存至当前路径
如:/tmp/data_bak =>保存至/tmp/

  • format: 压缩包种类,“zip”, “tar”, “bztar”,“gztar”
  • root_dir: 要压缩的文件夹路径(默认当前目录)
  • owner: 用户,默认当前用户
  • group: 组,默认当前组
  • logger: 用于记录日志,通常是logging.Logger对象
  1. #将 /data 下的文件打包放置当前程序目录
  2. import shutil
  3. ret = shutil.make_archive("data_bak", 'gztar', root_dir='/data')
  4.  
  5. #将 /data下的文件打包放置 /tmp/目录
  6. import shutil
  7. ret = shutil.make_archive("/tmp/data_bak", 'gztar', root_dir='/data')

  

shutil 对压缩包的处理是调用 ZipFile 和 TarFile 两个模块来进行的,详细:
zipfile压缩&解压缩

  1. import zipfile
  2.  
  3. # 压缩
  4. z = zipfile.ZipFile('laxi.zip', 'w')
  5. z.write('a.log')
  6. z.write('data.data')
  7. z.close()
  8.  
  9. # 解压
  10. z = zipfile.ZipFile('laxi.zip', 'r')
  11. z.extractall(path='.')
  12. z.close()

  

tarfile压缩&解压缩

  1. import tarfile
  2.  
  3. # 压缩
  4. >>> t=tarfile.open('/tmp/egon.tar','w')
  5. >>> t.add('/test1/a.py',arcname='a.bak')
  6. >>> t.add('/test1/b.py',arcname='b.bak')
  7. >>> t.close()
  8.  
  9. # 解压
  10. >>> t=tarfile.open('/tmp/egon.tar','r')
  11. >>> t.extractall('/egon')
  12. >>> t.close()

  

四,subprocess模块

  我们经常需要通过Python去执行一条系统命令或脚本,系统的shell命令是独立于你的python进程之外的,每执行一条命令,就是发起一个新进程,通过python调用系统命令或脚本的模块在python2有os.system,

  1. >> os.system('uname -a')
  2. Darwin Alexs-MacBook-Pro.local 15.6.0 Darwin Kernel Version 15.6.0: Sun Jun 4 21:43:07 PDT 2017; root:xnu-3248.70.3~1/RELEASE_X86_64 x86_64
  3. 0

  

这条命令的实现原理是什么呢?(视频中讲,解释进程间通信的问题...)

除了os.system可以调用系统命令,,commands,popen2等也可以,比较乱,于是官方推出了subprocess,目地是提供统一的模块来实现对系统命令或脚本的调用

The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several older modules and functions:

  • os.system
  • os.spawn*

The recommended approach to invoking subprocesses is to use the run() function for all use cases it can handle. For more advanced use cases, the underlying Popen interface can be used directly.

The run() function was added in Python 3.5; if you need to retain compatibility with older versions, see the Older high-level API section.

三种执行命令的方法

  • subprocess.run(*popenargs, input=None, timeout=None, check=False, **kwargs) #官方推荐

  • subprocess.call(*popenargs, timeout=None, **kwargs) #跟上面实现的内容差不多,另一种写法

  • subprocess.Popen() #上面各种方法的底层封装

run()方法

Run command with arguments and return a CompletedProcess instance.The returned instance will have attributes args, returncode, stdout and stderr. By default, stdout and stderr are not captured, and those attributes will be None. Pass stdout=PIPE and/or stderr=PIPE in order to capture them.

If check is True and the exit code was non-zero, it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute, and output & stderr attributes if those streams were captured.

If timeout is given, and the process takes too long, a TimeoutExpired exception will be raised.

The other arguments are the same as for the Popen constructor.

  使用参数运行命令并返回一个CompletedProcess实例。返回的实例将具有属性args、returncode、stdout和stderr。默认情况下,stdout和stderr没有被捕获,这些属性将是None。通过stdout=管道和/或stderr=管道来捕获它们。

  如果检查为真,退出代码为非零,则会产生一个称为processerror。CalledProcessError对象将在returncode属性和output & stderr中拥有返回代码。

属性,如果这些流被捕获。

  如果给定了超时,并且进程花费的时间太长,将会抛出一个超时过期的异常。

其他参数与Popen构造函数相同。

标准写法

  1. subprocess.run(['df','-h'],stderr=subprocess.PIPE,stdout=subprocess.PIPE,check=True)

  涉及到管道|的命令需要这样写

  1. subprocess.run('df -h|grep disk1',shell=True) #shell=True的
  2. 意思是这条命令直接交给系统去执行,不需要python负责解析

  

call()方法

  1. #执行命令,返回命令执行状态 , 0 or 非0
  2. >>> retcode = subprocess.call(["ls", "-l"])
  3.  
  4. #执行命令,如果命令结果为0,就正常返回,否则抛异常
  5. >>> subprocess.check_call(["ls", "-l"])
  6. 0
  7.  
  8. #接收字符串格式命令,返回元组形式,第1个元素是执行状态,第2个是命令结果
  9. >>> subprocess.getstatusoutput('ls /bin/ls')
  10. (0, '/bin/ls')
  11.  
  12. #接收字符串格式命令,并返回结果
  13. >>> subprocess.getoutput('ls /bin/ls')
  14. '/bin/ls'
  15.  
  16. #执行命令,并返回结果,注意是返回结果,不是打印,下例结果返回给res
  17. >>> res=subprocess.check_output(['ls','-l'])
  18. >>> res
  19. b'total 0\ndrwxr-xr-x 12 alex staff 408 Nov 2 11:05 OldBoyCRM\n'

  

Popen()方法

常用参数:

  1. argsshell命令,可以是字符串或者序列类型(如:list,元组)
  2.  
  3. stdin, stdout, stderr:分别表示程序的标准输入、输出、错误句柄
  4.  
  5. preexec_fn:只在Unix平台下有效,用于指定一个可执行对象(callable object),
  6. 它将在子进程运行之前被调用
  7.  
  8. shell:同上
  9.  
  10. cwd:用于设置子进程的当前目录
  11.  
  12. env:用于指定子进程的环境变量。如果env = None,子进程的环境变量将从父进程中继承。

  

下面这2条语句执行会有什么区别?

  1. a=subprocess.run('sleep 10',shell=True,stdout=subprocess.PIPE)
  2. a=subprocess.Popen('sleep 10',shell=True,stdout=subprocess.PIPE)

  

区别是Popen会在发起命令后立刻返回,而不等命令执行结果。这样的好处是什么呢?

如果你调用的命令或脚本 需要执行10分钟,你的主程序不需卡在这里等10分钟,可以继续往下走,干别的事情,每过一会,通过一个什么方法来检测一下命令是否执行完成就好了。

Popen调用后会返回一个对象,可以通过这个对象拿到命令执行结果或状态等,该对象有以下方法

  1. poll()
  2. Check if child process has terminated. Returns returncode
  3.  
  4. wait()
  5. Wait for child process to terminate. Returns returncode attribute.
  6.  
  7. terminate()
  8. 终止所启动的进程Terminate the process with SIGTERM
  9.  
  10. kill()
  11. 杀死所启动的进程 Kill the process with SIGKILL
  12.  
  13. communicate()
  14. 与启动的进程交互,发送数据到stdin,并从stdout接收输出,然后等待任务结束
  15.  
  16. send_signal(signal.xxx)
  17.   发送系统信号
  18.  
  19. pid 
  20.   拿到所启动进程的进程号

  

  1. >>> a = subprocess.Popen('python3 guess_age.py',stdout=subprocess.PIPE,stderr=subprocess.PIPE,stdin=subprocess.PIPE,shell=True)
  2.  
  3. >>> a.communicate(b'22')
  4.  
  5. (b'your guess:try bigger\n', b'')

  

五,configparser模块

此模块用于生成和修改常见配置文档,当前模块的名称在 python 3.x 版本中变更为 configparser。

configparser用于处理特定格式的文件,其本质上是利用open来操作文件。

来看一个好多软件的常见配置文件格式如下

配置文件的格式与windows ini文件类似,可以包含一个或多个节(section),每个节可以有多个参数(键=值)

  1. [DEFAULT]
  2. ServerAliveInterval = 45
  3. Compression = yes
  4. CompressionLevel = 9
  5. ForwardX11 = yes
  6.  
  7. [bitbucket.org]
  8. User = hg
  9.  
  10. [topsecret.server.com]
  11. Port = 50022
  12. ForwardX11 = no

  

想要生成这样一个文档怎么做?

  1. import configparser
  2.  
  3. config = configparser.ConfigParser()
  4. config["DEFAULT"] = {'ServerAliveInterval': '45',
  5. 'Compression': 'yes',
  6. 'CompressionLevel': '9'}
  7.  
  8. config['bitbucket.org'] = {}
  9. config['bitbucket.org']['User'] = 'hg'
  10. config['topsecret.server.com'] = {}
  11. topsecret = config['topsecret.server.com']
  12. topsecret['Host Port'] = '50022' # mutates the parser
  13. topsecret['ForwardX11'] = 'no' # same here
  14. config['DEFAULT']['ForwardX11'] = 'yes'
  15. with open('example.ini', 'w') as configfile:
  16. config.write(configfile)

  

Config Parser方法

  1. 1config=ConfigParser.ConfigParser()
  2. 创建ConfigParser实例
  3.  
  4. 2config.sections()
  5. 返回配置文件中节序列
  6.  
  7. 3config.options(section)
  8. 返回某个项目中的所有键的序列
  9.  
  10. 4config.get(section,option)
  11. 返回section节中,option的键值
  12.  
  13. 5config.add_section(str)
  14. 添加一个配置文件节点(str)
  15.  
  16. 6config.set(section,option,val)
  17. 设置section节点中,键名为option的值(val)
  18.  
  19. 7config.read(filename)
  20. 读取配置文件
  21.  
  22. 8config.write(obj_file)
  23. 写入配置文件

  

常见异常

异常 描述
ConfigParser.Error 所有异常的基类
ConfigParser.NoSectionError 指定的section没有找到
ConfigParser.DuplicateSectionError 调用add_section() 时,section名称已经被使用
ConfigParser.NoOptionError 指定的参数没有找到
ConfigParser.InterpolationError 当执行字符串插值时出现问题时,出现异常的基类
ConfigParser.InterpolationDepthError 当字符串插值无法完成时,因为迭代次数超过了最大的范围,所以无法完成。InterpolationError的子类
InterpolationMissingOptionError 当引用的选项不存在时,会出现异常。InterpolationError的子类
ConfigParser.InterpolationSyntaxError 当产生替换的源文本不符合所需的语法时,就会出现异常。InterpolationError的子类。
ConfigParser.MissingSectionHeaderError 当试图解析一个没有分段标题的文件时,会出现异常。
ConfigParser.ParsingError 当试图解析文件时发生错误时,会出现异常
ConfigParser.MAX_INTERPOLATION_DEPTH 当raw参数为false时,get()的递归插值的最大深度。这只适用于ConfigParser类

练习:

  1. >>> import configparser
  2. >>> config = configparser.ConfigParser()
  3. >>> config.sections()
  4. []
  5. >>> config.read('example.ini')
  6. ['example.ini']
  7. >>> config.sections()
  8. ['bitbucket.org', 'topsecret.server.com']
  9. >>> 'bitbucket.org' in config
  10. True
  11. >>> 'bytebong.com' in config
  12. False
  13. >>> config['bitbucket.org']['User']
  14. 'hg'
  15. >>> config['DEFAULT']['Compression']
  16. 'yes'
  17. >>> topsecret = config['topsecret.server.com']
  18. >>> topsecret['ForwardX11']
  19. 'no'
  20. >>> topsecret['Port']
  21. '50022'
  22. >>> for key in config['bitbucket.org']: print(key)
  23. ...
  24. user
  25. compressionlevel
  26. serveraliveinterval
  27. compression
  28. forwardx11
  29. >>> config['bitbucket.org']['ForwardX11']
  30. 'yes'

  

其他增删该查语法

  1. import configparser
  2.  
  3. config = configparser.ConfigParser()
  4.  
  5. #---------------------------------------------查
  6. print(config.sections()) #[]
  7.  
  8. config.read('example.ini')
  9.  
  10. print(config.sections()) #['bitbucket.org', 'topsecret.server.com']
  11.  
  12. print('bytebong.com' in config)# False
  13.  
  14. print(config['bitbucket.org']['User']) # hg
  15.  
  16. print(config['DEFAULT']['Compression']) #yes
  17.  
  18. print(config['topsecret.server.com']['ForwardX11']) #no
  19.  
  20. for key in config['bitbucket.org']:
  21. print(key)
  22.  
  23. # user
  24. # serveraliveinterval
  25. # compression
  26. # compressionlevel
  27. # forwardx11
  28.  
  29. print(config.options('bitbucket.org'))#['user', 'serveraliveinterval', 'compression', 'compressionlevel', 'forwardx11']
  30. print(config.items('bitbucket.org')) #[('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes'), ('user', 'hg')]
  31.  
  32. print(config.get('bitbucket.org','compression'))#yes
  33.  
  34. #---------------------------------------------删,改,增(config.write(open('i.cfg', "w")))
  35.  
  36. config.add_section('yuan')
  37.  
  38. config.remove_section('topsecret.server.com')
  39. config.remove_option('bitbucket.org','user')
  40.  
  41. config.set('bitbucket.org','k1','11111')
  42.  
  43. config.write(open('i.cfg', "w"))
  44.  
  45. 增删改查

  

  1. [group1]
  2. k1 = v1
  3. k2:v2
  4.  
  5. [group2]
  6. k1 = v1
  7.  
  8. import ConfigParser
  9.  
  10. config = ConfigParser.ConfigParser()
  11. config.read('i.cfg')
  12.  
  13. # ########## 读 ##########
  14. #secs = config.sections()
  15. #print secs
  16. #options = config.options('group2')
  17. #print options
  18.  
  19. #item_list = config.items('group2')
  20. #print item_list
  21.  
  22. #val = config.get('group1','key')
  23. #val = config.getint('group1','key')
  24.  
  25. # ########## 改写 ##########
  26. #sec = config.remove_section('group1')
  27. #config.write(open('i.cfg', "w"))
  28.  
  29. #sec = config.has_section('wupeiqi')
  30. #sec = config.add_section('wupeiqi')
  31. #config.write(open('i.cfg', "w"))
  32.  
  33. #config.set('group2','k1',11111)
  34. #config.write(open('i.cfg', "w"))
  35.  
  36. #config.remove_option('group2','age')
  37. #config.write(open('i.cfg', "w"))

  

python 关于操作文件的相关模块(os,sys,shutil,subprocess,configparser)的更多相关文章

  1. python关于操作文件的相关模块(os,sys,shutil,subprocess,configparser)

    一:os模块 os模块提供了许多允许你程序与操作系统直接交互的功能 功能 说明 os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径 os.chdir("dirna ...

  2. Python常用模块os & sys & shutil模块

    OS模块 import os ''' os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径 os.chdir("dirname") 改变当前脚本工作目录: ...

  3. Python常用模块(logging&re&时间&random&os&sys&shutil&序列化&configparser&&hashlib)

    一. logging(日志模块) 二 .re模块 三. 时间模块 四. random模块 五. os模块 六. sys模块 七. shutil模块 八. 序列化模块(json&pickle&a ...

  4. Python模块 - os , sys.shutil

    os 模块是与操作系统交互的一个接口 os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径 os.chdir("dirname") 改变当前脚本工作目录: ...

  5. Python与CSV文件(CSV模块)

    Python与CSV文件(CSV模块)   1.CSV文件 CSV(逗号分隔值)格式是电子表格和数据库最常用的导入和导出格式.没有“CSV标准”,因此格式由许多读写的应用程序在操作上定义.缺乏标准意味 ...

  6. 字符编码和Python代码操作文件

    字符编码和Python代码操作文件 读写模式之a模式 # a模式 只追加模式 # 路径不存在:自动创建 with open(r'a.txt','a',encoding='utf8') as f: pa ...

  7. Python中操作mysql的pymysql模块详解

    Python中操作mysql的pymysql模块详解 前言 pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同.但目前pymysql支持python3.x而后者不支持 ...

  8. 在Python中操作文件之truncate()方法的使用教程

    在Python中操作文件之truncate()方法的使用教程 这篇文章主要介绍了在Python中操作文件之truncate()方法的使用教程,是Python入门学习中的基础知识,需要的朋友可以参考下 ...

  9. 模块random+os+sys+json+subprocess

    模块random+os+sys+json+subprocess 1. random 模块   (产生一个随机值) import random 1 # 随机小数 2 print(random.rando ...

随机推荐

  1. Cocos2D中的Framerate状态

    对于额外绘制调试物理引擎的支持,Cocos2D同样可以绘制概述计数器,尤其是帧速率(framerate)显示. 为了启用这些概述计数器标签,你只需添加如下一行代码,比如说在AppDelegate.m里 ...

  2. Java进阶(二十)解疑答惑之何时字符串才算真正为空?

    解疑答惑之何时字符串才算真正为空? 在一次编码过程中,有一个现象一直困扰着自己,经过后台的不断调试,才发现原来有时候字符串的空非空.测试代码如下: // medname可为药品名称或药品ID Stri ...

  3. 11_Eclipse中演示Git版本的创建,历史版本的修改,创建分支,合并历史版本和当前版本

     1 执行以下案例: 某研发团队2011年初开发了一款名为Apollo的信息系统,目前已发布v1.0版本.此项目初期已有部分基础代码, 研发团队再此基础代码上经过3个月的努力发布了一个功能相对完备 ...

  4. STL - priority_queue(优先队列)

    优先级队列priority_queue 最大值优先级队列.最小值优先级队列 优先级队列适配器 STL priority_queue 用来开发一些特殊的应用. priority_queue<int ...

  5. anndroid 模糊引导界面

    先上两张图,后面补上代码 我们以前的写法是在需要显示模糊引导的地方,写一个布局,然后第一次使用的时候显示出来.但是这样做代码结构不清晰,所以我们有必要将这些View独立出来,写成一个自定义的View ...

  6. 安卓笔记-- ListView点击和长按监听

    其中点击监听为setOnItemClickListener() 具体实现代码如下 listView.setOnItemClickListener(new AdapterView.OnItemClick ...

  7. Nginx的内部(进程)模型

    nginx是以多进程的方式来工作的,当然nginx也是支持多线程的方式的,只是我们主流的方式还是多进程的方式,也是nginx的默认方式.nginx采用多进程的方式有诸多好处. (1)nginx在启动后 ...

  8. 关于NSString和NSMutableString的相关用法和基本介绍

    Objective-C 中核心处理字符串的类是 NSString 与 NSMutableString ,这两个类最大的区别就是NSString 创建赋值以后该字符串的内容与长度不能在动态的更改,除非重 ...

  9. 网络最短路径Dijkstra算法

    最近在学习算法,看到有人写过的这样一个算法,我决定摘抄过来作为我的学习笔记: <span style="font-size:18px;">/* * File: shor ...

  10. 恶补web之六:javascript知识(2)

    若要向html添加新元素,必须首先创建该元素,然后向一个已存在的元素追加该元素 <div id="div1"> <p id="p1">这 ...