Python:FileNotFoundError: [WinError 2] 系统找不到指定的文件

使用Jupyter notebook时运行此段代码:

from subprocess import check_output
print(check_output(["ls", "C:/Kaggle/Titanic/input"]).decode("utf8"))

出现错误:

FileNotFoundError                         Traceback (most recent call last)
<ipython-input-10-cf7fc002cdae> in <module>()
     32 # input directory
     33 from subprocess import check_output
---> 34 print(check_output(["ls", "C:/Kaggle/Titanic/input"]).decode("utf8"))
     35 #import os
     36 #print(os.listdir('C:/Kaggle/Titanic/input'))

~\Anaconda3\lib\subprocess.py in check_output(timeout, *popenargs, **kwargs)
    374 
    375     return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
--> 376                **kwargs).stdout
    377 
    378 

~\Anaconda3\lib\subprocess.py in run(input, capture_output, timeout, check, *popenargs, **kwargs)
    451         kwargs['stderr'] = PIPE
    452 
--> 453     with Popen(*popenargs, **kwargs) as process:
    454         try:
    455             stdout, stderr = process.communicate(input, timeout=timeout)

~\Anaconda3\lib\subprocess.py in __init__(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags, restore_signals, start_new_session, pass_fds, encoding, errors, text)
    754                                 c2pread, c2pwrite,
    755                                 errread, errwrite,
--> 756                                 restore_signals, start_new_session)
    757         except:
    758             # Cleanup if the child failed starting.

~\Anaconda3\lib\subprocess.py in _execute_child(self, args, executable, preexec_fn, close_fds, pass_fds, cwd, env, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, unused_restore_signals, unused_start_new_session)
   1153                                          env,
   1154                                          os.fspath(cwd) if cwd is not None else None,
-> 1155                                          startupinfo)
   1156             finally:
   1157                 # Child is launched. Close the parent's copy of those pipe

FileNotFoundError: [WinError 2] 系统找不到指定的文件。
  • 原因

因为使用的是Windows,默认情况下,Windows不符合POSIX。例如,没有ls二进制文件。因此,子进程无法找到该文件ls,从而发出一个FileNotFoundError。

  • 解决办法
  1. 可以在Windows上安装微软的Bash,它会给你ls。
  2. 列出目录更简单的方法是使用os.listdir:
import os
print(os.listdir('C:/Kaggle/Titanic/input'))

结果展示:[‘gender_submission.csv’, ‘test.csv’, ‘train.csv’]

注:摘自stackoverflow

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值