我正在尝试用Python编写一个小过程,在文件中写入(附加会更好)一行,如下所示:
def getNewNum(nlist):
newNum = ''
for i in nlist:
newNum += i+' '
return newNum
def writeDoc(st):
openfile = open("numbers.txt", w)
openfile.write(st)
newLine = ["44", "299", "300"]
writeDoc(getNewNum(newLine))
但是当我运行这个时,我得到一个错误:
openfile = open("numbers.txt", w)
NameError: global name 'w' is not defined
如果我放下“w”参数表,我会得到另一个错误:
line 9, in writeDoc
openfile.write(st)
IOError: File not open for writing
我正紧跟着(我希望)什么是here。
当我试图附加新行时,也会发生同样的情况。我该怎么解决?
问题在于
writeDoc()
中的open()调用中的文件模式规范不正确。w
需要(一对单引号或双引号)在其周围,即引用docsre文件模式:
Re:“如果我删除“w”参数,则会出现另一个错误:…IOError:文件未打开以供写入”
这是因为如果指定了no文件模式,那么默认值是
'r'
ead,这解释了文件未打开进行“写入”的消息,而是打开进行“读取”的消息。有关Reading/Writing files和有效模式规范的详细信息,请参阅本Python文档。
可以将数据追加到文件,但您当前正在尝试设置写入文件的选项,这将覆盖现有文件。
此外,您的实现会导致
open()
方法查找声明为w
的参数。但是,您需要传递字符串值以指示append选项,该选项由一个括在引号中的表示。相关问题 更多 >
编程相关推荐