[英]Python passing user input of name of file to open
I don't understand why something this simple isn't very intuitive. 我不明白为什么这么简单的东西不是很直观。
This is what I have so far: 这是我到目前为止的内容:
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()
Why can't I pass the sys.stdin that was assigned to the variable filename to the 'if' statement: 为什么不能将分配给变量文件名的sys.stdin传递给'if'语句:
`if file.startswith(filename):`?
I tried: 我试过了:
if file.startswith(str(filename)):
if file.startswith("'" + filename + "'")
if file.startswith(filename):
no options seem to "go through" and no errors pop up. 没有选项似乎“通过”,并且没有错误弹出。
It just pretends like I didn't pass anything. 只是假装我什么都没有通过。 Any help?
有什么帮助吗? Thanks.
谢谢。
A line, whether read from stdin or from a file, includes a newline character. 一行,无论是从stdin还是从文件中读取,都包含换行符。 It seems unlikely that any of your filenames end in a newline.
您的任何文件名似乎都不可能以换行符结尾。
But don't use sys.stdin.readline
to get input from the user. 但是不要使用
sys.stdin.readline
从用户那里获取输入。 Use the appropriately-named input
function: 使用适当命名的
input
函数:
filename = input("Enter name of file on Desktop:")
(Note, in Python 2.x you should use raw_input
rather than input
.) (请注意,在Python 2.x中,应使用
raw_input
而不是input
。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.