Python 打开文件时出现名称错误

Python 打开文件时出现名称错误,python,python-3.x,Python,Python 3.x,我试图构建一个函数,要求用户输入文件名,打开文件,读取文件内容,在屏幕上打印文件内容,然后关闭文件。如果不存在这样的文件,那么脚本崩溃也没关系。当我运行这个函数时,它给了我:NameError:name'myInput'没有定义,我不知道如何修复它 以下是我到目前为止的情况: printinput“请输入要打开的文件名”。+myInput 使用openrC:\Python32\getty.txt,“r”作为内嵌: 数据=infle.read 打印数据 帮助如果可以..在第一行中,您有: prin

我试图构建一个函数,要求用户输入文件名,打开文件,读取文件内容,在屏幕上打印文件内容,然后关闭文件。如果不存在这样的文件,那么脚本崩溃也没关系。当我运行这个函数时,它给了我:NameError:name'myInput'没有定义,我不知道如何修复它

以下是我到目前为止的情况:

printinput“请输入要打开的文件名”。+myInput 使用openrC:\Python32\getty.txt,“r”作为内嵌: 数据=infle.read 打印数据


帮助如果可以..

在第一行中,您有:

print(input('Please enter the name of a file that you want to open.' + myInput))
您是否定义了myInput?你需要定义它。如果在该行之前没有定义它,脚本将崩溃

这可以从您的有用错误消息中获得:

NameError:未定义名称“myInput”


这意味着变量myInput没有定义,因此编译器不知道放在那里的内容。

在第一行中,您有:

print(input('Please enter the name of a file that you want to open.' + myInput))
您是否定义了myInput?你需要定义它。如果在该行之前没有定义它,脚本将崩溃

这可以从您的有用错误消息中获得:

NameError:未定义名称“myInput”

这意味着变量myInput没有定义,因此编译器不知道放在那里的是什么。

myInput是一个未定义的变量,使用它我无法理解您的想法

也许在你展示代码的地方…:

print(input('Please enter the name of a file that you want to open.' + myInput))
with open(r"C:\Python32\getty.txt", 'r') as infile:
你的意思其实很不一样,比如…:

myInput = input('Please enter the name of a file that you want to open.')
with open(myInput, 'r') as infile:
…?

myInput是一个未定义的变量,使用它我无法理解您的想法

也许在你展示代码的地方…:

print(input('Please enter the name of a file that you want to open.' + myInput))
with open(r"C:\Python32\getty.txt", 'r') as infile:
你的意思其实很不一样,比如…:

myInput = input('Please enter the name of a file that you want to open.')
with open(myInput, 'r') as infile:

…?

我想这样做可以解决你的问题

fileName = raw_input("Please enter the name of a file that you want to open. ")
fileObject = open(fileName, "r")
fileText = fileObject.read()
print(fileText)

我想这样可以解决你的问题

fileName = raw_input("Please enter the name of a file that you want to open. ")
fileObject = open(fileName, "r")
fileText = fileObject.read()
print(fileText)

您是否尝试过使用原始输入代替输入?myInput在哪里定义?原始输入不起作用。也许我需要定义我的输入,但我不知道如何…你试过用原始输入代替输入吗?我的输入定义在哪里?原始输入不起作用。也许我需要定义我的输入,但我不知道如何。。。