View Full Version : [Python] salvataggio testo.
VBProgramming
21-11-2007, 07:20
Come faccio a salvare in un file txt delle stringhe in determinate righe?
es, voglio che il file di testo venga cosi:
gasfsgafsagfsga
gahsfsga
ahsg
come vedete, il testo è posto in righe differenti. Come faccio?
cdimauro
21-11-2007, 08:35
with open('Pippo.txt', 'w') as f:
f.write('''gasfsgafsagfsga
gahsfsga
ahsg''')
oppure così:
Stringa = '''gasfsgafsagfsga
gahsfsga
ahsg'''
with open('Pippo.txt', 'w') as f:
f.write(Stringa)
oppure così:
with open('Pippo.txt', 'w') as f:
f.write('gasfsgafsagfsga')
f.write('')
f.write('')
f.write('')
f.write(' gahsfsga')
f.write('ahsg')
o ancora così:
Lista = ['gasfsgafsagfsga\n', '\n', '\n', '\n', ' gahsfsga\n', 'ahsg\n']
with open('Pippo.txt', 'w') as f:
f.writelines(Lista)
o infine (ma ci saranno altre versioni, sicuramente :D) così:
Lista = ['gasfsgafsagfsga', '', '', '', ' gahsfsga', 'ahsg']
with open('Pippo.txt', 'w') as f:
f.writelines(Stringa + '\n' for Stringa in Lista)
;)
cdimauro
21-11-2007, 14:33
Mi sono accorto che nel terzo esempio c'è un errore: va aggiunto un \n alla fine di ogni stringa, altrimenti non verrà scritto su file il fine linea.
VBProgramming
21-11-2007, 15:36
ma non c'è un comando tipo
writelines[1] (cosi che scriva nella linea 1)?
cdimauro
21-11-2007, 16:38
ma non c'è un comando tipo
writelines[1] (cosi che scriva nella linea 1)?
E' un file, non una lista. Per giunta è un file di testo, dove le righe possono (e normalmente hanno) una lunghezza diversa.
Trattare un file come un insieme di stringhe (di lunghezza variabile) ovviamente è possibile, ma devi crearti un tuo oggetto che si comporti in questo modo.
Quindi una
f.writelines(1, 'Pippo')
è fattibilissima, ma la devi realizzare tu. ;)
vBulletin® v3.6.4, Copyright ©2000-2025, Jelsoft Enterprises Ltd.