4

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.

asked Nov 29, 2019 at 23:17

2 Answers 2

2

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)

answered Nov 29, 2019 at 23:32
Sign up to request clarification or add additional context in comments.

Comments

1

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])
answered Nov 29, 2019 at 23:45

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.