How to write files in python
After study how to open and close file in Python , then open a file then we will write some random text into it by using the write() method . In order to write into a file in Python, we need to open it in write "w" for only writing (an existing file with the same name will be erased), append "a" or exclusive creation "x" mode. Since we didn't specify a mode , the mode (default) was set to r.
After executing the above program, we can see the file is created in the disk. When opening the file, we can see the file content like:
It is because write() method does not add a newline character ('\n') to the end of the string. So, you need to explicitly add '\n' to write write() method.
Now the contents of file look like:
By using "with" statement is the safest way to handle a file operation in Python because "with" statement ensures that the file is closed when the block inside with is exited.
Append data to text file in python
You can also append a new text to the already existing file or the new file. You need to open the file in append mode, by setting "a" or "ab" of "a+" as the mode. When you open with "a" mode, the write position will always be at the end of the file (an append). You can open with "a+" to allow reading, seek backwards and read (but all writes will still be at the end of the file).
After executing the program and open the file then you can see the file content like:
The method flush() flushes the internal buffer, like stdio's fflush. Python uses the operating system's default buffering unless you configure it do otherwise. Python automatically flushes the files when closing them. But you can also force flush the buffer to a file programmatically with the flush() method .
Writing Unicode text to a text file in Python
The Unicode standard describes how characters are represented by code points . A code point is an integer value, usually denoted in base 16 . Python represents Unicode strings as either 16- or 32-bit integers, depending on how the Python interpreter was compiled. Best practice, in general, use UTF-8 for writing to files.
The utf-8 is the most modern and universally usable encoding and it works in all web browsers, most text-editors and most terminals/shells.
As an alternative, you can use the codecs module . The low-level routines for registering and accessing the available encodings are found in the codecs module. A code point is an integer value, usually denoted in base 16. The most commonly used part of the codecs module is the codecs.open() function.