A very common automation task that we tackle with Python is to create text files as well as read and write data into those files.
Python delivers built-in functions to create and manipulate text files. In this short tutorial we’ll go through several key capabilities:
- Create a new text file from scratch in the current folder.
- Create a new text file in a different folder.
- Add text to an existing text file.
Let’s look into a couple of examples.
Creating a file in Python:
To create text files in python, you can use the open(“filename”, “accessmode”) function. The below code will create a file named mydocument.txt with Write access permissions. This file will get created under the folder where the code is getting executed.
f = open("mydocument.txt", mode = "w") f.write("This text is written in python") f.close
Note: when opening a file in Write (‘w’) mode, the current file contents will be truncated. Use this mode carefully.
Create a file under a different path:
To create a file under a path different from our working directory, we will have to make a slight change in the way we call the open function.
We’ll use open(r”filepath&name”, “accessmode”). The r before the file path ensure that the path name string is read as a raw string. The backslashes in the path will then be treated as literals and not as escape characters. Note that you will need to make sure that the provided directory is available in your operating system before running the code. Let’s take a look.
f = open(r"C:\Temp\mydocument.txt", "w") f.write("This text is written in python") f.close
A bit more robust version of the code- using the pathlib library:
from pathlib import Path dir_path = Path('C:\Temp') file_name = 'mydocument.txt' # check if directory exists if my_path.is_dir(): f = open (dir_path.joinpath(file_name),'w') print('File created') else: print('Directory doesn't exist)
Append text to an existing file:
As mentioned before, the files we created using “w” as access mode will overwrite all existing file contents. Hence we typically open files in append mode (“a”). Append will insert your text after the existing data. Let’s take a quick look.
#write f = open(r"mydocument.txt", "w") f.write("This text is written in python. ") f.close() #read f = open("mydocument.txt", "r") print("New text:",f.read()) #append f = open(r"mydocument.txt", "a") f.write("This text is added using Append.") f.close() #read f = open("mydocument.txt", "r") print("Append:",f.read())
New text: This text is written in python. Append: This text is written in python. This text is added using Append.