Hello Folks....!!!!
Today Let us look at how to write to files using python.
To write to a file, it must be opened in 'w' or
'w+' or 'a' modes. To recall file opening modes,
refer
this link.
The files are of two types:
- Text file: This kind of files contain terminators such as new line (\n).
- Binary file: These don't have any terminators. The content has to either binary data or you have to convert your data into binary format before writing.
write() method and 'w' or w+ mode
To write something to the file open it in either 'w' or 'w+' mode. Once
opened, keep the content you want to write in String format if you want to
write the whole paragraph as it is. Look at the example below.
It is not mandatory that you have to store the content into a data structure. You pass it directly as parameter to the write method. You can modify this as f.write("Hello Folks.....!!! Let us learn Python.") . If a file named sample_file2.txt exists in the specified path, it will be over written otherwise a new file will be created and the content will be written to it. The snap shot of created file is given below.
write() method and 'a' mode
Instead of over writing, one can continue from the end of the file opened. For
this the file must be simply opened in 'a' (append) mode and rest are same.
Look at the code and output given below.
code:
Output:
writeline() method
This is used when the content need to be written is in a list data structure.
This provides the facility for formatting the text. Each element in the list
will be written in a new line if you append a '\n' at the end of each element
in the list. Look at the code snippet and the outcome given below.
code:
output:
Note that the contents have been over written as I have opened the same
sample_file2.txt which i used previously.
Next Topic👉
Comments
Post a Comment