Data manipulation in Python needs to create the file if the file does not exist. The open() method creates a file if it does not exists. We need to pass the required mode value. We will understand Ways to create a file if not exist in Python
What is Python Open()?
The Python open() method opens the file and returns a file object. It takes multiple arguments. The main argument is the first parameter is the FilePath and the second is an optional file mode.
- FilePath: It is a file path along with the filename.
- mode(optional): This is string specifies in which mode we are opening the file. If not provided default mode is ‘r’ which means opening the text file in reading mode.
|w||open file for writing plain text create a new file if not exists or truncate the file if exists.|
|r||open file for reading plain text|
|w+||open file for writing and reading plain text, create a new file if not exists or truncate the file if exists.|
|r+||open file for writing and reading plain text|
|a||Open File in append mode and content is appended to the end of file|
|a+||Open File in append mode if exists and append content to the end of file or create a new file and append content|
Sample File :sampledata.txt
This is a sample file that already exists and we are using in our program examples. It is present in the current directory where your code is.
This is devenum.com This is Python file post Keep exploring
Disadvanatge of using writing mode
If we are looking for a solution creating a new file only if it does not exist. Then using the open() method (‘w’, ‘w+’) mode will truncate the already exists file. We can use only these modes when we have to create a new file. Let us understand the problem with an example.
with open('sampledata.txt','w+') as fileobj: fileobj.write('appending to file') with open('sampledata.txt','r') as fileobj: #read each line at once with readline() line = fileobj.readline() while line: print(line.strip()) line = fileobj.readline()
as we can see output the all the contents of already exists sample file “sampledata.txt” has been truncated and file is created with new contents
appending to file
1. Create file if it does not exist by Using append mode
The file open() method “a+” mode is used to open a file for both appending and reading. It appends text at the end of the file if the file exists. If the file does not exist, it creates a new file for reading and writing. It will not truncate the file and append the content at end of the file as shown in the example below.
with open('sampledata.txt','a+') as fileobj: fileobj.write('appending to file\n') with open('sampledata.txt','r') as fileobj: #read each line at once with deadline() line = fileobj.readline() while line: print(line.strip()) line = fileobj.readline()
This is devenum.com This is Python file post Keep exploring appending to file
2. Create a file if it does not exist by Using the os. path.exists() method
The python os modules exists() method allows us to find out if a directory or file exists at a specific path. The exists() method returns TRUE if a file or directory exists else return FALSE.
import os file_path = 'sampledata.txt' mode = 'a' if os.path.exists(file_path) else 'w' with open(file_path, mode) as f: f.write('hi,there!\n')
This is devenum.com This is Python file post Keep exploring appending to file hi, there
3. Create file if not exist Using the Pathlib touch() method
In this example we can use the Pathlib module touch() method in Python version 3.4 and above.
Steps to Create file if not exist using Pathlib
- Install Pathlib Using cmd “pip install Pathlib” and import using from pathlib import Path.
- By using method touch(exist_ok =True) parameter checking if file exists at given path if exists we are appending text else creating new file.
from pathlib import Path #file in current directory myfile = Path('sampledata.txt') # will create a new file, if it exists will append text myfile.touch(exist_ok =True) with open(myfile,'a+') as fileobj: fileobj.write('how are you!\n')
This is devenum.com This is Python file post Keep exploring appending to file hi, there how are you!