使用目录路径作为用户输入的正确方法是什么?

2024-06-02 04:38:51 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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+")

Tags: thetext用户目录foropenusersdirectory
3条回答

我觉得你应该试试这样的:

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

相关问题 更多 >