简体   繁体   English

在python 2.7中从用户输入打开文件

[英]Open a file from user input in python 2.7

How would I open a file by asking for user input?如何通过要求用户输入来打开文件? After raw_input("PROMPT") requests filename.txt from the user, I get the error code:raw_input("PROMPT")从用户请求filename.txt后,我得到错误代码:

TypeError: coercing to Unicode: need string or buffer, file found类型错误:强制转换为 Unicode:需要字符串或缓冲区,找到文件

which tells me I need to convert the user input to a string, or format it a different way.这告诉我我需要将用户输入转换为字符串,或以不同的方式对其进行格式化。

What is the correct way of telling Python selectfile means "open this file"?告诉 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())

The issue is in the lines -问题在于——

selectfile = file(raw_input("Enter Filename: "), 'r')
with open(selectfile, 'r') as inF:

You need to open the filename (which is inputted from user) directly, as below -您需要直接打开文件名(从用户输入),如下所示 -

with open(raw_input("Enter Filename: "),'r') as inF:

Also, there seems to be an indentation issue in your code, seems like you really don't want to use with command for openning the input file, you may want to do -此外,您的代码中似乎存在缩进问题,您似乎真的不想使用with命令来打开输入文件,您可能想要这样做 -

inF = open(raw_input("Enter Filename: "),'r')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM