我正在尝试编写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,因为这是文件所在的位置。
答案 0 :(得分:2)
您使用的os.walk
输出错误。
abspath
与程序的当前工作目录相关,而文件位于root
指定的目录中。所以你想用
file = os.path.join(root, file)
答案 1 :(得分:1)
您的问题是在使用os.path.abspath()。该函数所做的全部工作就是将当前工作目录附加到该函数的任何参数上。在wc的l选项之前,您还需要具有-。我认为此修复程序可能会对您有所帮助:
import os
directory = input("Enter directory name: ")
full_dir_path = os.path.abspath(directory)
for root,dirs,files in os.walk(full_dir_path):
for file in files:
full_file_path = os.path.join(root, file)
print(full_file_path) #Checking to see the path
subprocess.call(['wc','-l',full_file_path])