Python Write Text FilePython Python File
In this tutorial we will learn how to use Python to write text file with different mode to overwrite or append existing file and how to write Unicode charater to a text file.
Append content to the end of existing file with mode ‘a’
For example we have the file named test.txt with content as below and located in the same folder of your Python code.
To append to existing file’s content we use ‘a’ for mode argument when open file for writing in Python.
f = open('test.txt', 'a') f.write('\nHappy Coding!') f.close()
Overwrite existing file with mode ‘w’
To overwrite existing file we use ‘w’ for mode argument when open file for writing in Python.
f = open('test.txt', 'w') f.write('This file has been overwrite.') f.close()
After execute the Python code above we will get the file as below.
Create new file with mode ‘x’
To creating a completely new file Python open() built-in method support ‘x’ for mode argument. In this mode the Python application will failing if the file already exist. For example assump that we have test.txt file already exist on your folder.
f = open('test.txt', 'x') f.write('This is new file') f.close()
If we execute the Python code above we will get result.
Traceback (most recent call last): File ".\create_new_file.py", line 1, in <module> f = open('test.txt', 'x') FileExistsError: [Errno 17] File exists: 'test.txt'
Modify file name to test2.txt
f = open('test2.txt', 'x') f.write('This is new file') f.close()
Write list of strings to text file using writelines() method
The Python code example below will show you how to use writelines() to write list of strings to text file.
f = open('test3.txt', 'w') data = ['Hello from toricode.com\n', 'Happy', ' ', 'Coding!'] f.writelines(data) f.close()
Write Unicode character to text file with UTF-8 encoding
To write Unicode charater Python open() method support encoding=‘utf-8’ argument.
f = open('test4.txt', 'w', encoding='utf-8') f.write('Việt Nam\n') f.write('日本\n') f.write('中国\n') f.close()