文章内容

2020/4/11 16:20:39,作 者: 黄兵

python No such file or Directory

python在操作文件的时候,如果出现如下错误:

python: can't open file 'myfile.txt': [Errno 2] No such file or directory

或者是如下错误:

IOError : No such file or directory

出现问题的原因:

文件不存在,或者目录错误。


解决方案:

1、使用绝对路径(absolute),而不是使用相对路径(relative paths)

例如:

E:/Code/Access_Log_Analysis/write_to_file.py

2、通过__file__实现跨平台

如果上面的绝对路径(absolute)改变,可能是程序迁移,部署到远程等,导致路径改变,路径写死就会出现错误。

通过下面的代码,即使路径改变,也依然可以解决问题:

# path: 'file_storage/access_log/2020_04/access_log-2020_4_11-9_44_21.csv'
_prefixes_date = time.strftime("%Y_%m", time.localtime())
cwd_path = 'file_storage\\access_log\\' + _prefixes_date + '\\'
file_path = os.path.join(self._current_work_path, cwd_path + 'access_log-' + self._prefixes_time + '.csv')
# 文件目录不存在,新建目录,0755->即用户具有读/写/执行权限,组用户和其它用户具有读写权限;
if not os.path.exists(cwd_path):
    os.makedirs(cwd_path, 0o755)
return file_path

像这样的代码基于从Python的magic __file__变量派生当前路径 ,在Windows和Linux上在本地和服务器上运行都没有问题。

同时上面的代码:

if not os.path.exists(cwd_path):
    os.makedirs(cwd_path, 0o755)

判断是否存在当前路径,如果不存在新建当前路径,并赋予权限。

os.makedirs()方法用于递归创建目录。

同时需要注意:

path_01 = 'Test\\path_01\\path_02\\path_03'

os.mkdir()os.makedirs()的区别:

os.mkdir()创建路径中的最后一级目录,即:只创建path_03目录,而如果之前的目录不存在并且也需要创建的话,就会报错。

os.makedirs()创建多层目录,即:Test,path_01,path_02,path_03,如果都不存在的话,会自动创建。


参考资料:

1、No such file or Directory?

2、【Linux】Linux中的0644 和 0755的权限

3、python 判断目录和文件是否存在,若不存在即创建

4、Python os.makedirs() 方法

5、Python中os.mkdir()与os.makedirs()的区别及用法

分享到:

发表评论

评论列表

user-ico

佛系派 on 回复 有用(0

干货,标记一下

游客v3bL on 2020-04-13 17:08:03

博主回复:感谢