What is the proper way to take a directory path as user input?

让人想犯罪 __ 提交于 2019-11-30 12:48:31

I think you should try something like:

import sys
import os

user_input = raw_input("Enter the path of your file: ")

assert os.path.exists(user_input), "I did not find the file at, "+str(user_input)
f = open(user_input,'r+')
print("Hooray we found your file!")
#stuff you do with the file goes here
f.close()

It seems you want to check if the directory exists.

If so, see os.path.isdir.

os.path.isdir(path)
    Return True if path is an existing directory.
    This follows symbolic links, so both islink()
    and isdir() can be true for the same path.

You can do like this:

s = raw_input();
if os.path.isdir(s):
    f = open(s, "r+")
else:
    print "Directory not exists."

I figured it out... I forgot to add the file extension at the end of the file name on my directory path; I did not notice that I was cutting it off by just copying/pasting the name of my file.... the program works now... thank you all!

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!