簡體   English   中英

將目錄路徑作為用戶輸入的正確方法是什么?

[英]What is the proper way to take a directory path as user 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 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+")

我想你應該嘗試類似的東西:

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

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."

我想通了......我忘了在目錄路徑上的文件名末尾添加文件擴展名; 我沒有注意到我只是通過復制/粘貼我的文件名來切斷它....程序現在正在運行...謝謝大家!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM