Python Create File in Directory: Guide

You can create a file using the open() function in Python. Here is an example:

import os

path = '/path/to/your/directory'
filename = 'example.txt'

# 拼接路径和文件名
file_path = os.path.join(path, filename)

# 创建文件并写入内容
with open(file_path, 'w') as file:
    file.write('Hello, world!')

In the example above, the path and filename for creating the file are firstly specified. Next, the os.path.join() function is used to concatenate the path and filename together, forming the complete file path. Finally, the open() function is used to open the file in write mode (‘w’) and write the content.

bannerAds