Python文件目录判断和创建

本文探讨了Python中文件操作的常见问题,包括如何检查文件或目录的存在性、正确处理包含特殊字符的文件名及路径,以及如何遍历包含中文名称的文件夹。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值