要在指定目錄創(chuàng)建文件,可以使用Python的open()
函數(shù)來創(chuàng)建文件并指定路徑。下面是一個(gè)示例代碼:
import os
directory = "path/to/directory" # 指定目錄的路徑
file_name = "new_file.txt" # 新文件的名稱
file_path = os.path.join(directory, file_name) # 合并目錄和文件名
# 創(chuàng)建文件
with open(file_path, 'w') as file:
file.write("Hello, world!")
print(f"文件 {file_name} 已創(chuàng)建在目錄 {directory}")
替換path/to/directory
為你想要?jiǎng)?chuàng)建文件的目錄路徑,運(yùn)行上面的代碼即可在指定目錄創(chuàng)建一個(gè)名為new_file.txt
的文件,并在文件中寫入Hello, world!
。