dude123345
dude123345

Reputation: 45

Python Directory Path

I am trying to write a python script to use the linux command wc to input the amount of lines in a file. I am iterating through a directory inputted by the user. However, whenever I get the absolute path of a file in the directory, it skips the directory it is in. So, the path isn't right and when I call wc on it, it doesn't work because it is trying to find the file in the directory above. I have 2 test text files in a directory called "testdirectory" which is located directly under "projectdirectory".

Script file:

   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])

This is what I get when running the program:

   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

I don't know why the path isn't /home/joe/Documents/projectdirectory/testdirectory/file2 since that is where the file is located.

Upvotes: 4

Views: 94

Answers (2)

sadiela
sadiela

Reputation: 106

Your issue is in the use of os.path.abspath(). All that this function does is appends the current working directory onto whatever the argument to the function is. You also need to have a - before the l option for wc. I think this fix might help you:

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])

Upvotes: 1

cadolphs
cadolphs

Reputation: 9597

You're using the output of os.walk wrong.

abspath is related to your program's current working directory, whereas your files are in the directory as specified by root. So you want to use file = os.path.join(root, file)

Upvotes: 2

Related Questions