以下是应该允许用户从目录中查看文件列表并键入一个文件以打开的功能。一切似乎都工作顺利,并且没有出现语法错误,但是当我键入文件名时,我想打开它却没有任何作用。有解决方案吗?
def openFile(dirName):
"""Allows user to view list of files in directory and view them."""
lyst = os.listdir(dirName)
for element in lyst: print(element)
userinput = input('Enter file name: ')
if userinput in lyst:
open(userinput)
else:
print('\nFile not in directory\n')
return (userinput, 'r')
最初您有:
if userinput in lyst:
file = open(userinput)
[...]
return (userinput, 'r')
userinput
是字符串,而不是文件。例如,userinput
可能是“ myfile.txt
”。
因此,您正在返回一个元组("myfile.txt", 'r')
。字母“ r”不是以只读模式打开文件,而只是字母“ r
”。您返回了一对短字符串,其中一个总是字母'r
'
也许您想要以下内容?
if userinput in lyst:
file = open(userinput, mode='r')
[...]
return file
这很危险,因为您必须记住以后要关闭文件。
另一个问题是,您需要先进入用户指定的文件夹,然后才能打开该文件夹中的文件。
以下两段代码之一应该适合您:
import pathlib as pl
import os
def openFile(dirName):
"""Allows user to view list of files in directory and view them."""
lyst = os.listdir(dirName)
for element in lyst:
print(element)
filename = input('Enter file name: ')
if filename in lyst:
os.startfile(pl.Path(dirName) / filename)
else:
print('\nFile not in directory\n')
return
或
import pathlib as pl
import os
def openFile(dirName):
"""Allows user to view list of files in directory and view them."""
lyst = os.listdir(dirName)
for element in lyst:
print(element)
filename = input('Enter file name: ')
if filename in lyst:
file = open(pl.Path(dirName) / filename, mode="r")
else:
print('\nFile not in directory\n')
return file # dangerous! don't forget to call file.close()!