# coding=utf-8 import os # 操做文件和目錄 print("1", os.getcwd()) # 獲取當前文件的目錄 print("2", os.path.realpath(__file__)) # __file__表示當前你正在編輯的文件 # os.mkdir('test_lemon.txt') # 新建目錄 # os.rmdir('python3.4') # 刪除目錄 # # current_dir = os.getcwd() # new_dir = os.path.join(current_dir, "python3.4") # os.mkdir(new_dir) print(os.listdir()) # 返回的數據是當前文件下全部文件->以列表顯示 print(os.path.isfile(__file__)) # 判斷當前編輯的文件是不是一個文件,返回布爾值 print(os.path.isdir(__file__)) # 判斷當前編輯的文件是不是一個目錄,返回布爾值 current_url = os.getcwd() print("當前文件夾的Path爲: ", current_url) print(os.path.split(os.getcwd())) # 返回的是元組類型,tuple,前面是目錄,最後一節是文件夾 print(os.path.split(os.path.realpath(__file__))[0]) print(os.path.exists("test.txt")) # 判斷是否存在,return是否爲布爾值
# coding=utf-8 ''' 對二進制文件和非二進制文件的讀/寫/追加/新建操做 ''' file_ = open('test_demo.txt', 'r') # 內置函數, # 絕對路徑/相對路徑 print(file_) # 同級 # read 只讀 write 只寫 append 追加 # 非二進制文件 r r+(可讀寫,追加) w w+ a a+(追加,追加+讀) # 二進制文件 rb rb+ wb wb+ ab ab+ ''' # 只讀的方式打開 file_ = open("test_demo.txt", 'r') res_1 = file_.read(5) res_2 = file_.read(4) print(res_1, res_2) ''' ''' # r+讀寫的方式,寫的內容會寫在文件的最後面 file_ = open("test_demo.txt", 'r+') file_.write('demo_test') res_1 = file_.read() print(res_1) ''' # w 只寫,若是不存在這個file的話,那麼會先新建,而後根據你的要求寫入內容 # w 只寫,若是這個file存在的話,那麼寫入的時候會覆蓋之前的內容 # w+ 讀寫 file_ = open('test_demo.txt', 'w+', encoding='utf-8') res_1 = file_.read(5) res_2 = file_.read(4) file_.write("權杖型_架構師1111") print(res_1, res_2) print(file_.tell()) # 獲取光標的位置 file_.close() # seek方法->>>>移動光標位置,(0,0)移動光標到頭部位置 # 第一個參數是要移動的字節,第二個參數是相對哪一個位置去移動 0頭部 1當前位置 2尾巴 # a+ 有新建文件的功能 file_test = open('test_ssss.txt', 'a+') file_test.write('selenium') print(file_test.read()) # 上下文管理器 with open as with open('test_111.txt', 'r+') as f: f.write('test') res_1 = f.read() print(res_1) f.close() # 關閉對文件的操做,避免過分佔用資源