os模块提供了大量的文件和目录操作方法函数。
读取文件获取目录一个常见的问题就是无法显示中文目录,网上找的解决方法均是通过重新设置编码方式,通过重新加载sys,设置系统编码方式
import os
import sys
reload(sys)
print "系统默认编码方式:",sys.getdefaultencoding()
sys.setdefaultencoding('utf8')
print "设置后系统的编码方式:",sys.getdefaultencoding()
print(os.path.abspath('coutry.txt'))
发现有个系统编码,win7和win10都是使用的是GBK编码,查询编码方式,在Windows平台下,进入DOS窗口,输入:chcp
936对应的编码格式为GBK。或者使用进入DOS窗口,在标题栏右键/属性,显示当前代码页为936--简体中文GBK
那如何获取当前文件的编码格式呢,使用chardet库中的detect()函数
import os
import sys
import chardet
print "系统默认编码方式:",sys.getdefaultencoding()
print(chardet.detect(os.path.abspath('coutry.txt')))
发现使用的是GB2312编码方式,所以对于中文乱码,就可以应当对每一个文件路径做编码转换 很简单 就是先按照 GB2312 decode 然后再按照 UTF-8 encode即可。
import os
#获取绝对路径
print(os.path.abspath('coutry.txt').decode('GBK').encode('utf-8'))
获取绝对路径的方法还有一个os.path._getfullpathname()函数
print(os.path._getfullpathname('coutry.txt'))
那如何获取当前文件所在的目录呢?看以下实例
import os
#获取绝对路径
print(os.path.abspath('coutry.txt').decode('GBK').encode('utf-8'))
#获取目录
print(os.path.dirname('coutry.txt'))
print(os.path.dirname('G:\资料\自动化测试\Exercise\XML\coutry.txt'))
print(os.path.dirname(os.path.abspath('coutry.txt').decode('GBK').encode('utf-8')))
abspath 可以打印出绝对路径(包含文件名):G:\资料\自动化测试\Exercise\XML\coutry.txt
dirname()如果只是给出文件的绝对路径,才能返回出具体的路径值,如果参数为文件名,则返回为空
os.path.dirname(os.path.dirname)获得文件的目录
那这样获取文件目录就有点麻烦,可以使用os模块中getcwd()获取当前文件目录
import os
print(os.path.dirname(os.path.abspath('coutry.txt').decode('GBK').encode('utf-8')))
print(os.getcwd().decode('GBK').encode('utf-8'))
有篇不错的介绍推荐一下,见介绍