Python 将目录路径作为用户输入的正确方式是什么?

Python 将目录路径作为用户输入的正确方式是什么?,python,raw-input,Python,Raw Input,下面是一段代码片段,我正试图使用它将目录路径作为用户的“原始输入”。从用户处获取输入后,我收到以下错误: Traceback (most recent call last): File "C:\Users\larece.johnson\Desktop\Python Programs\Hello World 2", line 14, in <module> f = open(str,"r+") #I o

下面是一段代码片段,我正试图使用它将目录路径作为用户的“原始输入”。从用户处获取输入后,我收到以下错误:

Traceback (most recent call last):
  File "C:\Users\larece.johnson\Desktop\Python Programs\Hello World 2", line 14, in <module>
    f = open(str,"r+")                                     #I open the text file here which the user gave me
IOError: [Errno 2] No such file or directory: 'C:/Users/larece.johnson/Desktop/Python Programs/BostonLog.log.2014-04-01'

我想你应该试试这样的东西:

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

您似乎想检查目录是否存在

如果是,请参阅

您可以这样做:

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

我想出来了。。。我忘了在我的目录路径的文件名末尾添加文件扩展名;我没有注意到我只是通过复制/粘贴我的文件名来切断它。。。。程序现在可以运行了。。。谢谢大家!

顺便说一句:
/
是斜杠;反斜杠应该是
\
。我认为一个问题可能是用户是否希望在输入时将文件路径放在引号中。我提供的脚本不需要引号。我正在使用Windows和Python 2.7 btw,如果它有区别的话。。。但是阅读你的答案。。。检查以确保路径存在是正确的,但它仍然返回不存在的消息。。。。我知道文件和路径存在,因为我转到文件所在的位置并检查“属性”以获取文件的位置,我还复制文件名并将其添加到路径的末尾。我将整个路径作为“输入”剪切粘贴到我的程序中。我不使用Windows,但这应该没什么关系。我会将脚本添加到一个名为test.py的文件中,并要求使用test.py作为输入,作为检查。。。并将其放入我的代码中自动打开(即f=open(“C:/Users/larece.johnson/Desktop/Python Programs/BostonLog.log.2014-04-01.log”),它会找到目录并运行。在Python中,我注意到当我在程序中输入要自动打开的目录时,我必须等待每个目录路径的名称“显示……我之所以提到这一点,是因为也许有一种方法可以让我以同样的方式以“原始输入”的形式进入目录。。。
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()
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.
s = raw_input();
if os.path.isdir(s):
    f = open(s, "r+")
else:
    print "Directory not exists."