2017-06-04 95 views
0

我不明白为什么这样简单的事情不是很直观。Python传递用户输入的文件名称来打开

这是我到目前为止有:

print("Enter name of file on Desktop:") 
    filename = sys.stdin.readline() 


    directory = os.path.join(os.path.expanduser("~"),"Desktop") 
     for subdir, dirs, files in os.walk(directory): 
      for file in files: 
       if file.startswith(filename): 
        f = open(os.path.join(subdir, file),'r+', encoding="Latin-1") 
        data = f.read() 
        print(data) 
        f.close() 

为什么我不能传递被分配到变量名 到sys.stdin的“如果”声明:

`if file.startswith(filename):`? 

我想:

if file.startswith(str(filename)): 
    if file.startswith("'" + filename + "'") 
    if file.startswith(filename): 

没有选择似乎“经历”,并没有错误弹出。

它只是假装我没有通过任何事情。任何帮助?谢谢。

+0

格式代码:使用适当命名input功能(注意,在Python 2.x的,你应该使用raw_input而非input)。只对代码的小块使用反引号。 – Carcigenicate

+0

此外,任何时候你得到错误,你需要发布他们 – Carcigenicate

回答

2

无论是从stdin还是从文件读取的行都包含一个换行符。你的文件名似乎不太可能以换行符结束。

但是不要使用sys.stdin.readline从用户那里获得输入。由四个空格缩进

filename = input("Enter name of file on Desktop:") 

+0

我知道这是愚蠢的。谢谢。我得到它的工作。 –