Search code examples
pythondirectorydirectory-structure

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:

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