ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2019-10-06 01:58:39  阅读:224  来源: 互联网

标签:raw-input 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+")

解决方法:

我想你应该尝试类似的东西:

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

标签:raw-input,python
来源: https://codeday.me/bug/20191006/1857970.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有