【问题标题】:What is the proper way to take a directory path as user input?将目录路径作为用户输入的正确方法是什么?
【发布时间】:2014-04-08 13:54:14
【问题描述】:

下面是我试图用来将目录路径作为用户的“原始输入”的代码的 sn-p。从用户获取输入后,我收到以下错误:

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'

忽略我在下面所做的事情,是否有一种特殊的方式我应该从用户那里获取路径以便 Python 接受它?

比如我要查找的目录和文件是

C:/Users/larece.johnson/Desktop/Python Programs/BostonLog.log.2014-04-01
import re     #this library is used so that I can use the "search" function
import os     #this is needed for using directory paths and manipulating them 

str =""       #initializing string variable for raw data input

#print os.getcwd()
#f = open("C:/Users/larece.johnson/Desktop/BostonLog.log.2014-04-02.log","r+")

str = raw_input("Enter the name of your text file - please use / backslash when typing in directory path: ");  #User will enter the name of text file for me

f = open(str,"r+")

【问题讨论】:

  • 顺便说一句:/ 是斜线;反斜杠是\ 。

标签: python raw-input


【解决方案1】:

我认为您应该尝试以下方法:

    import sys
    import os

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

【讨论】:

  • 我认为一个问题可能是用户是否应该在输入时将文件路径放在引号中。我提供的脚本不需要引号。
  • 我正在使用 Windows 和 Python 2.7 顺便说一句,如果它有所作为......但是阅读你的答案......检查以确保路径存在是好的,但它仍然返回它不存在....我知道文件和路径存在,因为我转到文件所在的位置并检查“属性”以获取文件的位置,我还复制文件的名称并将其添加到路径的末尾.我将整个路径剪切并粘贴到我的程序中作为“输入”。
  • 我没有使用 Windows,但这应该没什么大不了的。我会将脚本放到一个名为 test.py 的文件中,并要求使用 test.py 作为输入,作为检查。
  • 我注意到的另一件事是,如果我采用我想要的路径......并将其放入我的代码中以自动打开(即 f = open("C:/Users/larece.johnson/ Desktop/Python Programs/BostonLog.log.2014-04-01.log),它会找到目录并且它会工作。在Python中我注意到当我进入程序内自动打开的目录时,我必须等待每个目录路径“名称”都显示出来......我提到这一点是因为也许有一种方法可以让我以同样的方式作为“原始输入”进入目录......
【解决方案2】:

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

如果是这样,请参阅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.

你可以这样做:

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-22
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多