参考博客:python创建文件和文件夹_ -CSDN博客_python 创建文件
创建文件夹
import os def mkdir(path): folder = os.path.exists(path) if not folder: #判断是否存在文件夹如果不存在则创建为文件夹 os.makedirs(path) #makedirs 创建文件时如果路径不存在会创建这个路径 print "--- new folder... ---" print "--- OK ---" else: print "--- There is this folder! ---" file = "G:\\xxoo\\test" mkdir(file) #调用函数
os.getcwd()可以查看py文件所在路径;
在os.getcwd()后边 加上 [:-4] + 'xxoo\\' 就可以在py文件所在路径下创建 xxoo文件夹
import os folder = os.getcwd()[:-4] + 'new_folder\\test\\' #获取此py文件路径,在此路径选创建在new_folder文件夹中的test文件夹 if not os.path.exists(folder): os.makedirs(folder)
在py文件路径下创建test的txt文件
import os def txt(name,text): #定义函数名 b = os.getcwd()[:-4] + 'new\\' # 实际使用中我把[:-4]删掉才得到正确的路径,这里对转载的博客存疑 if not os.path.exists(b): #判断当前路径是否存在,没有则创建new文件夹 os.makedirs(b) xxoo = b + name + '.txt' #在当前py文件所在路径下的new文件中创建txt file = open(xxoo,'w') file.write(text) #写入内容信息 file.close() print ('ok') txt('test','hello,python') #创建名称为test的txt文件,内容为hello,python
python判断文件是否存在的三种方式:Python判断文件是否存在的三种方法 - j_hao104 - 博客园 (cnblogs.com)
1.使用os模块
os模块中的os.path.exists()
方法用于检验文件是否存在。
- 判断文件是否存在
import os os.path.exists(test_file.txt) #True os.path.exists(no_exist_file.txt) #False
- 判断文件夹是否存在
import os os.path.exists(test_dir) #True os.path.exists(no_exist_dir) #False
可以看出用os.path.exists()
方法,判断文件和文件夹是一样。
其实这种方法还是有个问题,假设你想检查文件“test_data”是否存在,但是当前路径下有个叫“test_data”的文件夹,这样就可能出现误判。为了避免这样的情况,可以这样:
- 只检查文件
import os os.path.isfile("test-data")
通过这个方法,如果文件”test-data”不存在将返回False,反之返回True。
即是文件存在,你可能还需要判断文件是否可进行读写操作。
判断文件是否可做读写操作
使用os.access()
方法判断文件是否可进行读写操作。
语法:
os.access(path, mode)
path为文件路径,mode为操作模式,有这么几种:
-
os.F_OK: 检查文件是否存在;
-
os.R_OK: 检查文件是否可读;
-
os.W_OK: 检查文件是否可以写入;
-
os.X_OK: 检查文件是否可以执行
该方法通过判断文件路径是否存在和各种访问模式的权限返回True或者False。
import os if os.access("/file/path/foo.txt", os.F_OK): print "Given file path is exist." if os.access("/file/path/foo.txt", os.R_OK): print "File is accessible to read" if os.access("/file/path/foo.txt", os.W_OK): print "File is accessible to write" if os.access("/file/path/foo.txt", os.X_OK): print "File is accessible to execute"
2.使用Try语句
可以在程序中直接使用open()
方法来检查文件是否存在和可读写。
语法:
open()
如果你open的文件不存在,程序会抛出错误,使用try语句来捕获这个错误。
程序无法访问文件,可能有很多原因:
-
如果你open的文件不存在,将抛出一个
FileNotFoundError
的异常; -
文件存在,但是没有权限访问,会抛出一个
PersmissionError
的异常。
所以可以使用下面的代码来判断文件是否存在:
try: f =open() f.close() except FileNotFoundError: print "File is not found." except PermissionError: print "You don't have permission to access this file."
其实没有必要去这么细致的处理每个异常,上面的这两个异常都是IOError
的子类。所以可以将程序简化一下:
try: f =open() f.close() except IOError: print "File is not accessible."
使用try语句进行判断,处理所有异常非常简单和优雅的。而且相比其他不需要引入其他外部模块。
创建文件: