0

I am currently trying to get the file_path (suppose ~/hello_world/) as user input and list all the files inside this directory. I can do this exact same thing if I pass ~/hello_world as sys.argv however, I can't seem to get it work if I take it as an input. I am trying to work the code from any directory and user inputted file path will be from /home/ubunut/... Here's my working code as sys.argv:

This code is intended for unix based os only for now.

if len(sys.argv) == 2:
    path = sys.argv[1]

files = os.listdir(path)
for name in files:
    print(name)

Here's the code I am trying to work with:

path = input("file_path: ")
files = os.listdir(path)
for name in files:
    print(name)

This is when it crashed with the following error:

Traceback (most recent call last):
  File "test.py", line 14, in <module>
    files = os.listdir(path)
FileNotFoundError: [Errno 2] No such file or directory: '~/hello_world/'

Thanks in advance.

O_o
  • 1,103
  • 11
  • 36
  • Your code works on my machine. Are you sure that the directory you're looking for exists? – CFV Sep 15 '18 at 09:55
  • Oh. I am trying to work with any directory. – O_o Sep 15 '18 at 09:57
  • In your first part of code you put the path variable declaration inside your if, but you are using it outside the if block, so the variable could be not initialized. In fact if you don't insert any argument, your code doesn't work. – CFV Sep 15 '18 at 09:58
  • For the first part of code, you will have to run it something like this, python3 script_name.py ~/backup/ because, it's taking the argument from sys arg. I thought I made myself clear. – O_o Sep 15 '18 at 10:00

1 Answers1

1

You need to expand the ~ like in the answer to this question

The following worked for me

import os

path = input("enter filepath: ")

for f in os.listdir(os.path.expanduser(path)):
    print(f)
Souperman
  • 5,057
  • 1
  • 14
  • 39