我正在学习Python作为初学者,并且有一个我无法弄清楚的问题。我需要编写函数来允许用户设置/给文件命名然后输入内容。
我收到的错误消息是:"Str' object is not callable
。我不知道如何解决这个问题。请你救我。非常感谢!
代码如下:
=========================================
WRITE = "w"
APPEND = "a"
fName = ""
def fileName(): #to define name of the file.
fName = input("Please enter a name for your file: ")
fileName = open(fName, WRITE)
return fileName
#now to define a function for data entry
dataEntry = ""
def enterData():
dataEntry = input("Please enter guest name and age, separated by a coma: ")
dataFile = open(fName, APPEND(dataEntry))
fName.append(dataEntry)
return dataFile
#to determine if it's the end of data entry
moreEntry = input("Anymore guest: Y/N ")
while moreEntry != "N":
enterData() #here to call function to repeat data entry
fName.close()
fileName()
enterData()
print("Your file has been completed!")
fileContents = fName.readline()
print(fileContents)
答案 0 :(得分:0)
我运行了代码并且......我将错误视为第14行
14 dataFile = open(fName, APPEND(dataEntry))
fName未在此范围内声明。您的功能间距已关闭。也许你打算按顺序运行所有代码而不是部分代码?
实际上,fName是全局声明和定义的(第4行),在函数filename()中声明和定义(第6行)。
fName也在函数中引用(第7行)第14行调用失败
dataFile = open(fName, APPEND(dataEntry)) # fName has not been declared in function enterData()
我怀疑如果您重新排序行并且不使用函数(由于引用),您的代码将会起作用。另外,请关闭您的文件。 EG
f = open ("somefile.txt", "a+")
...
f.close() #all in the same block.
答案 1 :(得分:0)
感谢所有的投入。非常感激。我已经重新编写了一些代码,并首先将所有数据条目放入列表中,然后尝试将列表附加到文件中。它在某种程度上起作用(大约80%,也许!)
然而,我现在有另一个问题。当我尝试打开文件以附加列表时,它在代码(line31)旁边显示“没有这样的文件或目录”:“myFile = open(fName,APPEND)”。但我以为我宣布然后让用户在开头定义名称?我应该怎么做呢?
WRITE = "w"
APPEND = "a"
fName = ""
def fileName(): #to define name of the file.
fName = input("Please enter a name for your file: ")
fileName = open(fName, WRITE)
fileName.close()
return fileName
#now to define a function for data entry
dataEntry = ""
dataList = []
def enterData():
dataEntry = input("Please enter guest name and age, separated by a coma: ")
dataList.append(dataEntry)
return
fileName()
enterData()
#to determine if it's the end of data entry
moreEntry = input("Anymore guest: Y/N ")
if moreEntry == "Y":
enterData()
else:
print("Your file has been completed successfully!")
myFile = open(fName, APPEND)
myFile.append(dataList)
myFile.close()
fileContents = fName.readline()
print(fileContents)