OKPEDIA PYTHON EN

How to open a file for write in Python

Per scrivere un nuovo file di dati con Python, usare i metodi open, write e close.

f = open(namefile, 'w')
f.write(rec)
f.close()

The open method indicates the name of the file to be created and the type of write access 'w' (write).

The write method writes a single record.

Note. As an alternative to the write method, you can also use the print() function using the file attribute.

The close method closes the file when the write operation is complete.

Note. Questo script crea un nuovo file di dati. Non aggiunge dati a un file già esistente. Se il nome del file esiste, viene sovrascritto. Per aggiungere dati a un file esistente si utilizza l'attributo 'a' (append) al posto di 'w'.

Examples

Example 1 (write method)

To create the text file test.txt using the method write()

f = open('test.txt', 'w')
f.write('first record \n')
f.write('second record \n')
f.close()

The open method opens the file for writing (w).

The write method writes two records. An end-of-record or carriage return character must be added manually to each record (\n).

The close() method closes the file after writing is complete.

Example 2 (print function)

To create the text file test.txt using the function print().

f = open('test.txt', 'w')
print('first record', file=f)
print('second record', file=f)
f.close()

In this case the end-of-record character is not added, because the function print() inserts it automatically.

https://how.okpedia.org/en/python/how-to-open-a-file-for-write-in-python


Report an error or share a suggestion to enhance this page



FacebookTwitterLinkedinLinkedin