2012-07-03 22 views
9

Estoy tratando de escribir un pequeño procedimiento que escriba (anexar sería aún mejor) una línea en un archivo con Python, como este:Python IOError: El archivo no está abierto para escritura y el nombre global 'w' no está definido

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)) 

Pero cuando corro esto, me sale el error:

openfile = open("numbers.txt", w) 
NameError: global name 'w' is not defined 

Si me cae el Paremeter "w", tengo este otro error:

line 9, in writeDoc 
    openfile.write(st) 
IOError: File not open for writing 

Estoy siguiendo exactamente (espero) lo que es here.

Lo mismo ocurre cuando intento agregar la nueva línea. ¿Cómo puedo arreglar eso?

+1

Su función 'getNewNum' solo debería ser' '' .join (newLine) '. –

Respuesta

23

El problema está en la llamada open() en writeDoc() que la especificación del modo de archivo no es correcta.

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

Los w tiene que tener (un par de simple o doble) cita a su alrededor, es decir,

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

Citando el modo de archivo docs re:

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: "Si elimino el parámetro" w ", aparece este otro error: ..IOError: archivo no abierto para escribir"

Esto es porque si no se especifica el modo de archivo, el valor predeterminado es 'r' ead, lo que explica que el mensaje no esté abierto para "escritura", se haya abierto para "lectura".

Consulte este documento de Python para obtener más información sobre Reading/Writing files y las especificaciones de modo válidas.

+0

D'oh! No puedo creer que he estado usando Python por tanto tiempo y todavía hago tonterías como esta (y luego tengo que buscar lo que está pasando. Terminé omitiendo el modo por completo). – ArtOfWarfare

2

Es posible adjuntar datos a un archivo, pero actualmente está intentando establecer la opción de escribir en el archivo, que anulará un archivo existente.

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.

Además, los resultados de la ejecución en el método open() en busca de un parámetro declarado como w. Sin embargo, lo que desea es pasar el valor de la cadena para indicar la opción de agregar, que se indica mediante una combinación de comillas.

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