Python文件目录判断和创建

来源:互联网 发布:apache 域名泛解析 编辑:程序博客网 时间:2024/05/21 17:58
#coding=utf-8
'''
Created on 2014-3-24
@author: Bruce Liu
'''
import os

# 检测目录是否存在
print os.path.exists('test')
# 创建目录
os.mkdir("test1")
# 使用os.path.exists()方法可以直接判断文件是否存在。
print os.path.exists(r'test\1.TXT') 
fileName = "file_test.txt"
if os.path.isfile(fileName):
    print fileName + ' exits!'
else :
    print fileName + ' not exits!'
#===============================================================================
# open(fileName)     # 如果文件不存在,则会报错
# open(fileName, 'w')# 如果文件不存在,但是使用'w'参数,则会自动创建文件
#===============================================================================
dotFile = open(fileName, 'w')
if os.path.isfile(fileName):
    print fileName + ' exits!'
else :
    print fileName + ' not exits!'

问题是什么来着,在2.7.3下:
fileName = "d:\\2014-03-25 23:35:41.txt"
logFile = file(fileName, "w")
结果是:IOError: [Errno 22] invalid mode ('w') or filename: 'd:\\2014-03-25 23:35:41.txt'
fileName = "d:\\2014-03-25 23:35:41.txt"
logFile = file(fileName, "w")
结果又是这样:IOError: [Errno 22] invalid mode ('w') or filename: 'd:\x814-03-25 23:35:41.txt'
这是什么情况???

首先在单反斜杠的情况下,变成这种结果:d:\x814-03-25 23-44-10.txt,不解???
解决办法:
fileName = "d:\\2014-03-25 23-35-41.txt".decode(sys.getdefaultencoding()#注意双\\,一个\不行
logFile = file(fileName, "w")
OK,搞定。发现涉及到文件路径的时候,需要进行编码
而无论是单反斜杠,还是又反斜框情况下,文件创建都不成功的原因是,文件名中有冒号(:)

在打开文件目录时,并列出文件夹/文件时,为了能正确识别路径,并能正确显示路径下的中文文件夹/文件名称,如下做:
for lists in os.listdir('D:\\中文路径'.decode(sys.getdefaultencoding())):
        print lists


0 0
原创粉丝点击