共計(jì) 580 個(gè)字符,預(yù)計(jì)需要花費(fèi) 2 分鐘才能閱讀完成。
要打開(kāi)指定文件夾并添加內(nèi)容,可以使用 Python 的 os 模塊和 open 函數(shù)來(lái)實(shí)現(xiàn)。以下是一個(gè)示例代碼:
import os
folder_path = "path/to/your/folder"
file_name = "your_file.txt"
content = "This is the content you want to add"
# 檢查文件夾是否存在,如果不存在則創(chuàng)建
if not os.path.exists(folder_path):
os.makedirs(folder_path)
file_path = os.path.join(folder_path, file_name)
# 打開(kāi)文件并添加內(nèi)容
with open(file_path, "a") as file:
file.write(content)
print("Content added to the file successfully!")
在這個(gè)示例中,首先指定了要添加內(nèi)容的文件夾路徑、文件名和內(nèi)容。然后使用 os 模塊的 makedirs 函數(shù)來(lái)創(chuàng)建文件夾(如果不存在),然后使用 os.path.join 來(lái)構(gòu)建文件的完整路徑。最后使用 open 函數(shù)以追加模式打開(kāi)文件,并將內(nèi)容寫(xiě)入文件中。
請(qǐng)注意,這段代碼將在指定的文件夾中創(chuàng)建一個(gè)新文件(如果不存在),并將內(nèi)容添加到文件中。如果文件已經(jīng)存在,則會(huì)在文件的末尾添加內(nèi)容。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完