Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What am I doing incorrect in this directory search python code?

What am I doing wrong in the following source code and how can I fix that?

my_script.py

import subprocess
import os
import time
from pathlib import Path

def get_files(dir_str):
    onlyfiles = next(os.walk(dir_str))[2] 
    return onlyfiles


input_files_path_str = "$HOME"


def main():
    input_files_list = get_files(input_files_path_str)
    print(input_files_list)

if __name__=="__main__":
    main()

Output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

user_name@server_name:~$ python3 my_script.py
Traceback (most recent call last):
  File "my_script.py", line 19, in <module>
    main()
  File "my_script.py", line 15, in main
    input_files_list = get_files(input_files_path_str)
  File "my_script.py", line 7, in get_files
    onlyfiles = next(os.walk(dir_str))[2]
StopIteration
user_name@server_name:~$

>Solution :

os.walk does not expand the shell variables(In this case it’s $HOME) automatically.
You need to use os.path.expandvars api to expand it before supplying to get_files.

import os.path
input_files_list = get_files(os.path.expandvars(input_files_path_str))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading