如何通过询问用户输入来打开文件?在raw_input("PROMPT")
向用户请求filename.txt
后,我收到错误代码:
TypeError:强制转换为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())
答案 0 :(得分:1)
问题在于 -
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')