我需要帮助将文件(.txt)声明为用户输入并使用open方法打开文件

时间:2015-08-18 22:42:47

标签: python-2.7 text-files

这是我的代码(包含从用户获取文件名):

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'未定义

1 个答案:

答案 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,但如果您使用的是相对路径,则可以将其保留。