如何通过请求用户输入来打开文件?从用户filename.txt
raw_input("PROMPT")
请求后,我收到错误代码:
类型错误:强制到 Unicode:需要字符串或缓冲区,找到文件
这告诉我我需要将用户输入转换为字符串,或以不同的方式格式化它。
告诉 Python selectfile
意味着"打开此文件"的正确方法是什么?
selectfile = file(raw_input("Enter Filename: "), 'r')
with open(selectfile, 'r') as inF:
with open('outputfile.txt', 'w') as f:
for index, line in enumerate(inF):
if myString in line:
print "Search Term Found!"
f.write("Line %d has string: %s" % (index, line))
filename = "outputfile.txt"
myfile = open(filename)
lines = len(myfile.readlines())
问题出在行中 -
selectfile = file(raw_input("Enter Filename: "), 'r')
with open(selectfile, 'r') as inF:
您需要直接打开文件名(由用户输入),如下所示 -
with open(raw_input("Enter Filename: "),'r') as inF:
另外,您的代码中似乎存在缩进问题,似乎您真的不想使用with
命令来打开输入文件,您可能需要这样做 -
inF = open(raw_input("Enter Filename: "),'r')