我正在尝试编写一个python脚本来使用linux命令wc来输入文件中的行数。我正在迭代用户输入的目录。但是,每当我获取目录中文件的绝对路径时,它都会跳过它所在的目录。因此,该路径不正确,当我对其调用 wc 时,它不起作用,因为它正在尝试查找上面目录中的文件。我在名为“testdirectory”的目录中有 2 个测试文本文件,该目录直接位于“projectdirectory”下。
脚本文件:
import subprocess
import os
directory = raw_input("Enter directory name: ")
for root,dirs,files in os.walk(os.path.abspath(directory)):
for file in files:
file = os.path.abspath(file)
print(path) #Checking to see the path
subprocess.call(['wc','l',file])
这是我运行程序时得到的结果:
joe@joe-VirtualBox:~/Documents/projectdirectory$ python project.py
Enter directory name: testdirectory
/home/joe/Documents/projectdirectory/file2
wc: /home/joe/Documents/projectdirectory/file2: No such file or directory
/home/joe/Documents/projectdirectory/file1
wc: /home/joe/Documents/projectdirectory/file1: No such file or directory
我不知道为什么路径不是/home/joe/Documents/projectdirectory/testdirectory/file2 因为那是文件所在的位置。
最佳答案
您使用了 os.walk
的输出错误。
abspath
与程序当前的工作目录相关,而您的文件位于 root
指定的目录中。所以你想使用
file = os.path.join(root, file)
关于Python目录路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59111892/