【问题标题】:"No such file or directory" error when using "cat" in python在 python 中使用“cat”时出现“没有这样的文件或目录”错误
【发布时间】:2020-03-14 18:18:17
【问题描述】:

当我使用时

cat folder1/folder2/*_in.txt>>output.txt 

直接在终端中,它工作正常。

但是当我从 python 进程内部调用时,它显示错误"No such file or directory"

command = "cat "+path+"*_in.txt >> " + output_variable
print(command) # print exactly the same.
os.system(command) # error : cat: folder1/folder2/*_in.txt: No such file or directory

【问题讨论】:

  • os.system 绝对是一个shell
  • @Omer,这不是真的。 os.system(something) 致电 ['sh', '-c', something]sh 非常像一个外壳。
  • 对,删除了我的误导性评论。
  • 为什么使用os.system()而不是Subprocess模块​​?

标签: python file cat


【解决方案1】:

当没有匹配该模式的文件时会发生这种情况:

$ python -c 'import os; os.system("cat *.txt")'
cat: '*.txt': No such file or directory

$ echo 'Hello World' > myfile.txt

$ python -c 'import os; os.system("cat *.txt")'
Hello World

请注意,文件是相对于进程的当前工作目录 (os.getcwd()) 匹配的,而不是相对于 Python 文件。如果您无法确定文件的工作目录和正确的相对路径,请使用绝对路径。

【讨论】:

  • 我将代码更改为使用删除帖子的其他用户建议的代码!,我的意思是在 python 本身中使用 for 循环并且它可以工作。但我有另一个命令要运行:“chmod +x”+filename 并使用 os.command(),它给了我同样的问题。我尝试使用绝对路径。请注意,该文件位于同一文件夹中。
  • 我更喜欢直接使用 os.command 来了解它是如何工作的,所以我可以在其他命令中使用它。
  • 我的 Python 3.7.6 中没有 os.command(),我在文档中也找不到它
  • 对不起,我的意思是 os.system()。之间,请忽略我所说的关于 chmod 的内容,因为我发现了问题。但是,我仍然无法运行命令来连接所有 txt 文件。
  • 你能写一个简短的、独立的演示脚本,我可以在我的机器上运行来查看问题吗? (即MCVE)。
猜你喜欢
  • 2010-12-18
  • 1970-01-01
  • 2015-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多