Python IOError:未打开文件进行写入,未定义全局名称“w”

2024-09-28 05:26:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用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

当我试图附加新行时,也会发生同样的情况。我该怎么解决?


Tags: intxtfordef错误newlineopenwrite
2条回答

问题在于writeDoc()中的open()调用中的文件模式规范不正确。

openfile = open("numbers.txt", w)
                               ^

w需要(一对单引号或双引号)在其周围,即

openfile = open("numbers.txt", "w")
                                ^

引用docsre文件模式:

The first argument is a string containing the filename. The second argument is another string containing a few characters describing the way in which the file will be used.

Re:“如果我删除“w”参数,则会出现另一个错误:…IOError:文件未打开以供写入”

这是因为如果指定了no文件模式,那么默认值是'r'ead,这解释了文件未打开进行“写入”的消息,而是打开进行“读取”的消息。

有关Reading/Writing files和有效模式规范的详细信息,请参阅本Python文档。

可以将数据追加到文件,但您当前正在尝试设置写入文件的选项,这将覆盖现有文件。

The first argument is a string containing the filename. The second argument is another string containing a few characters describing the way in which the file will be used. mode can be 'r' when the file will only be read, 'w' for only writing (an existing file with the same name will be erased), and 'a' opens the file for appending; any data written to the file is automatically added to the end. 'r+' opens the file for both reading and writing. The mode argument is optional; 'r' will be assumed if it’s omitted.

此外,您的实现会导致open()方法查找声明为w的参数。但是,您需要传递字符串值以指示append选项,该选项由一个括在引号中的表示。

openfile = open("numbers.txt", "a") 

相关问题 更多 >

    热门问题