系統:Windows 7
語言版本:Anaconda3-4.3.0.1-Windows-x86_64
編輯器:pycharm-community-2016.3.2
Python:3.6.0
- 這個系列講講os模塊常用功能
- 本文介紹:新建文件夾及文本文件
Part 1:代碼
import os
current_dir = os.path.dirname(os.path.abspath(__file__))
# 創建文件夾
folder_name = "HelloWorld"
folder_address = os.path.join(current_dir, folder_name)
if not os.path.exists(folder_address):
os.mkdir(folder_address)
# 創建文件
txt_file_name = "HelloWorld.txt"
txt_file_address = os.path.join(current_dir, txt_file_name)
# 檢查文件是否存在,存在則刪除
if os.path.exists(txt_file_address):
os.remove(txt_file_address)
f = open(txt_file_address, 'w')
f.write("HelloWorld")
f.close()
代碼截圖
未執行代碼前:
執行代碼後:
Part 2:部分代碼解讀
os.mkdir(folder_address)
,創建新文件夾f = open(txt_file_address, 'w')
,打開一個文件,並進入寫入模式,若該文件不存在,則創建f.write("HelloWorld")
向文件中寫入HelloWorld信息。若想一行一行寫入,需要在每一行內容間增加f.write("\n")
f = open(txt_file_address, 'w')
f.write("HelloWorld")
f.write("\n")
f.write("HelloWorld")
f.write("\n")
f.write("HelloWorld")
f.write("\n")
f.write("HelloWorld")
f.close()
執行結果
4. 若不增加f.write("\n")
,如下
f = open(txt_file_address, 'w')
f.write("HelloWorld")
f.write("HelloWorld")
f.write("HelloWorld")
f.write("HelloWorld")
f.close()
結果如下
本文爲原創作品,歡迎分享朋友圈
常按圖片識別二維碼,關注本公衆號
Python 優雅 帥氣