2012-07-03 15 views
9

Sto provando a scrivere una piccola procedura che scrive (append sarebbe anche meglio) una riga in un file con Python, come questo:Python IOError: File non aperto per la scrittura e nome globale 'w' non definito

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

Ma quando ho eseguito questo, ottengo l'errore:

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

Se mi cade l'paremeter "w", ottengo questo altro errore:

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

Sto seguendo esattamente (spero) che cosa è here.

Lo stesso accade quando provo ad aggiungere la nuova linea. Come posso ripararlo?

+1

La funzione 'getNewNum' dovrebbe essere semplicemente' '' .join (newLine) '. –

risposta

23

Il problema è nella chiamata open() in writeDoc() che la specifica della modalità file non è corretta.

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

Le w deve avere (una coppia di singolo o doppio) cita intorno ad esso, vale a dire,

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

Per citare la modalità file 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.

Ri: "Se si rilascia il paremeter" w ", viene visualizzato questo altro errore: ..IOErrore: file non aperto per la scrittura"

Questo perché se viene specificata la modalità file no, il valore predefinito è 'r' ead, che spiega il messaggio relativo al fatto che il file non è aperto per "scrittura", è stato aperto per "lettura".

Vedere questo documento Python per ulteriori informazioni su Reading/Writing files e per le specifiche della modalità valida.

+0

D'oh! Non posso credere di aver usato Python per così tanto tempo e continuo a fare cose stupide come questa (e poi devo cercare cosa c'è di sbagliato. Alla fine ho omesso completamente la modalità.) – ArtOfWarfare

2

È possibile aggiungere dati a un file ma si sta attualmente tentando di impostare l'opzione per scrivere sul file, che sovrascriverà un file esistente.

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.

Inoltre, i risultati di implementazione nel metodo open() alla ricerca di un parametro dichiarato come w. Tuttavia, ciò che si desidera è passare il valore della stringa per indicare l'opzione di aggiunta, che è indicata da un racchiuso tra virgolette.

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