这是我的代码(包含从用户获取文件名):
def fileInput():
#below will be modified, below is for user input
filename=input('What is the filename (include .txt): ')
authorfile=open('home/brandon/filename.txt','r+')
##print authorfile.read(); - Deleted 8/11/15
return authorfile;
这是我得到的错误:
Traceback (most recent call last):
文件“/ media / brandon / Sony_32GM / Python Programs / author database_1.py”,第61行,in 的FileInput() 在fileInput中输入文件“/ media / brandon / Sony_32GM / Python Programs / author database_1.py”,第37行 filename = input('文件名是什么(包括.txt):') 文件“”,第1行,in NameError:名称'test1'未定义
答案 0 :(得分:0)
在Python 2.7中,输入将输入计算为表达式,因此如果您只想读取字符串,请使用raw_input:
def fileInput():
#below will be modified, below is for user input
filename=raw_input('What is the filename (include .txt): ')
authorfile=open('/home/brandon/' + filename,'r+')
##print authorfile.read(); - Deleted 8/11/15
return authorfile;
此外,如果您使用的是绝对文件路径,则需要/ before home,但如果您使用的是相对路径,则可以将其保留。