共計(jì) 396 個(gè)字符,預(yù)計(jì)需要花費(fèi) 1 分鐘才能閱讀完成。
要在指定目錄創(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!
。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完