Python目录路径

标签 python

我正在尝试编写一个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/

相关文章:

python - str。包含在pandas数据框中创建新列

python - 将数据附加到python字典

python - 属性错误 : module 'torchtext.data' has no attribute 'Field'

python - 计算两个文件的行差异的最有效方法是什么?

python - literal_eval(f'{}') 会被滥用来执行来自外部源的代码吗?

python - 如何为每列绘制具有不同线条颜色的 Pandas 数据框?

python - Gitlab CI : Failed building wheel for opencv-python

python - 使用 Jug,如何在多处理模式下运行嵌套循环?

python - 对不同的拟合模型重复使用逻辑回归对象

python - 应用引擎 : ImportError: No module named Crypto. 哈希