Multiple Ways to Create File in Python

Python provides numerous functions to deal with files and to perform operations on them. The operations such as writing to a file, appending to a file, opening a file, etc. are done using the inbuilt Python functions. To create a file, the “open()” function is used along with the “w” and “x” modes in Python. 

In this blog, listed below ways are discussed to create a file in Python using numerous examples:

How to Create a File in Python?

To create a file, the “open()” function is used along with “w” mode or “x” mode. The syntax of the “open()” function is shown below:

open(file_name, mode)

There are various modes used in the “open()” function such as “a” mode is used to append data to the file, “r” mode is used to read the file, “w” mode is used to write data to the file. We will use “w” mode to create the file and write the content on it. We can also use “x” mode to create an empty file.

Example 1: Create a File if Not Exist in a Specific Path

In the below code, a file is created on the specific path:

Code:

import os
file_location = r'C:\Users\p\Downloads\ILf\sample.txt'
if os.path.exists(file_location):
    print('File Already Exists')
else:
    with open(file_location, 'w') as fp:
        fp.write('Hello and Welcome to My Guide!')
  • Firstly, the “os” module is imported.
  • The path of the file along with the name is assigned to a variable named “file_location”.
  • The “os.path.exists()” function takes the location and checks whether the file is present or not in the specified path.
  • If the file does not exist then the “with open()” function creates the file and opens it in “w” writing mode.
  • The “write()” function is used to write the specific data to a file.

Output:

The file named “sample.txt” has been created.

Example 2: Create a File in a Particular Directory

The below code is utilized to create a file in a particular/absolute path of the directory:

Code:

with open(r'C:\Users\p\Downloads\ILf\sample.txt', 'w') as fp:
    fp.write('Python Guide')
    pass
  • The “with open()” function creates the file by accepting the complete file path and “w” writing mode as an argument.
  • The “write()” function is used to write the content to the file.

Output:

The file has been created.

Example 3: Create a File With Date and Time Attribute

The “datetime” module is used along with the “open()” function to create a file with date and time in Python:

Code:

import datetime
time_now = datetime.datetime.now()
string_time = time_now.strftime("%Y-%m-%d_%H-%M-%S")
filename = "example"
fileformat = ".txt"
file_new = filename + "_" + string_time + fileformat

with open(file_new, "w") as f:
    f.write("Python Guide! ")
  • The “datetime” module is imported at the start of the program.
  • The “datetime.datetime.now()” function retrieves the current time and date.
  • The current time is converted to string format “%Y-%m-%d_%H-%M-%S” using the “time_now.strftime()” function.
  • The name of the file and the format is assigned to variables named “filename” and “fileformat”.
  • By using the concatenation operator the filename, current time, and format are concatenated to make one string.
  • The “with open()” function is used to create the file and open the file in “w” mode. The “write()” function is used to write the data to a file.

Output:

Date and time are appended to the file named “example.txt” when it is created in the program.

Example 4: Create an Empty Text File

The below code is used to create an empty text file:

Code:

file_new = open('sample.txt', 'x')
file_new.close()

The “open()” function accepts the file name and mode “x” to create an empty file.

Output:

The empty text file has been created successfully.

Example 5: Create a New Python File With Permission

The following code is used to create a new file with permission:

Code:

import os
new_file_name = "sample.txt"
with open(new_file_name, mode='w', encoding='utf-8', newline='') as file:
    os.chmod(new_file_name, 0o644)
    file.write("Hello and Welcome to itslinuxfoss!")

file_stat_info = os.stat(new_file_name)
print(oct(file_stat_info.st_mode & 0o777))
  • We import the “os” module at the start of the program.
  • The name of the file “sample.txt” is set to a variable named “new_file_name”.
  • Next, the “open()” function is used to open the file with write permission (‘w’), using the specified encoding (‘utf-8’) and newline character (‘\n’). 
  • The “os.chmod()” function is used to set the permission for the new file.
  • According to the permission value “0o644”, the owner of the file has both read and write permissions, while members of the group and others have only read permissions.
  • The “write()” function is used to write the content to the file.
  • The “os.stat()” function is used to retrieve the file status information, including the file mode (permissions), for the new file.
  • Finally, the “oct()” function is used to convert the file mode to an octal representation, and then prints it to the console. 
  • The “& 0o777” operation is used to mask out any additional bits that may be set in the file mode value.

Output:

The file has been created with permission.

Conclusion

The “open()” function is used with the “w” mode to create a file with writing permissions or use the open() function with “x” mode to create an empty file. Use the “if-else” and “os.path.exists()” functions along with the “open()” function to generate a file if it does not present on the specified path. We can create a file in a specific directory by defining the absolute path. This Python tutorial provides various ways to create a file in Python.