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. example
my_file = open("my_file.txt", "w") # Open a file
my_file.write("This is my first line") # write a line to the file
my_file.write("This is my second line") # write one more line to the file
my_file.close() # close the file
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:
This is my first lineThis is my second line
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.
example
my_file = open("my_file.txt", "w") # Open a file
my_file.write("This is my first line\n") # write a line to the file
my_file.write("This is my second line\n") # write one more line to the file
my_file.close()
Now the contents of file look like:
This is my first line
This is my second line
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.
example
with open("my_file.txt", "w") as my_file:
my_file.write("This is my first line\n") # write a line to the file
my_file.write("This is my second line\n") # write one more line to the file
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). example
with open("my_file.txt", "a") as my_file:
my_file.write("This is my third line\n") # write a line to the file
my_file.write("This is my fourth line\n") # write one more line to the file
After executing the program and open the file then you can see the file content like:
This is my first line
This is my second line
This is my third line
This is my fourth line
Python flush()
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 . example
with open("my_file.txt", "w+") as my_file:
my_file.write("This is my first line \n")
# do some work
str = "This is my second line"
my_file.write(str)
my_file.write('\n')
my_file.flush()
# some other work
my_file.write("This is my third line \n")
my_file.flush()
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.
encoding = "utf-8"
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.
example
import io
str = u'\u5E73\u621015'
with io.open("my_file.txt", "w+", encoding="utf-8") as my_file:
my_file.write(str)
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.
example
import codecs
str = u'\u5E73\u621015'
with codecs.open("my_file.txt", "w+", encoding="utf-8") as my_file:
my_file.write(str)
Related Topics
- How to open and close a file in Python
- How to read a file properly in Python
- How to read a file line by line in Python
- How to use Split in Python
- Directory Operations Using Python
- How to check that a file or directory exists with Python
- File Access Mode in Python
- Difference between read, readline and readlines | python
- Python file positions | seek() and tell()
- How to Copy a File using Python