Python-os-04-新建文件夾及文本文件

微信公衆號原文

系統: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()

代碼截圖
1.png

未執行代碼前
2.png

執行代碼後
3.png

Part 2:部分代碼解讀

  1. os.mkdir(folder_address),創建新文件夾
  2. f = open(txt_file_address, 'w'),打開一個文件,並進入寫入模式,若該文件不存在,則創建
  3. 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.png
4. 若不增加f.write("\n"),如下

f = open(txt_file_address, 'w')
f.write("HelloWorld")
f.write("HelloWorld")
f.write("HelloWorld")
f.write("HelloWorld")
f.close()

結果如下
5.png

本文爲原創作品,歡迎分享朋友圈

常按圖片識別二維碼,關注本公衆號
Python 優雅 帥氣
12x0.8.jpg

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章