python第六節隨堂筆記(os&file)

__author__ = 'Administrator'
import os
#import 包名.模塊名
#import class_0518.class_0527_6


#調用函數?包名.模塊名.函數名(參數)
#class_0518.class_0527_6.choose_drink()


#form 包名.模塊名 import 函數名
#from class_0518.class_0527_6 import choose_drink


#調用函數 函數名(參數)
#choose_drink()


"""
#os 操作文件和目錄
#print('1',os.getcwd())#獲取當前文件的目錄
print('2',os.path.realpath(__file__))
#__file__表示當前弄正在剪輯的文件
#os.mkdir("box")#新建一個目錄


current=os.getcwd()
new_dir=os.path.join(current,"python7/五月","666")
#new_dir=os.path.join(current,"python8","六月")
#join 路徑拼接/確保最後一個參數之前的路徑存在才能添加
#os.mkdir(new_dir)


print(os.listdir())#返回的數據是列表類型
print(os.path.isfile(__file__))#布爾值
print(os.path.isdir(__file__))#布爾值


#print(current)
print(os.path.split(current))#返回元祖
print(os.getcwd())
print(os.path.split(os.path.realpath(__file__))[0])
print(os.path.exists("text.txt"))"""


#file 文件操作
#file=open("text.txt",'w',encoding="utf-8")#內置函數 可以打開一個文件
#相對路徑(跟當前文件是同級)   絕對路徑
#read 只讀 write 只寫 append 追加
#非二進制文件 r r+ w w+ a a+
#二進制文件 rb rb+ wb wb+ ab ab+
#r 只讀的方式打開 r+讀寫的方式打開 寫的內容會寫在文件的最後面
#w 只寫 如果不存在這個file的話,那麼會先新建,然後根據你的要求寫入內容
#      如果這個文件存在的話,那麼就是直接覆蓋,重寫
# w+ 讀寫 同w
#a+ 同w
file=open("text_1.txt",'a+',encoding="utf-8")
file.write("hello python")
print(file.tell())
file.seek(0,0)#移到頭部 第一個參數是你要移動的字節
#第二個參數是你相對哪個位置去移動0 頭部 1 當前位置 2 尾巴


#file.seek(1,1)#正數 0 1 2,負數-1
print(file.tell())
#result1=file.read(2)
#result2=file.read(4)
result=file.read()
file.write("wuyue")
print(result)
#print(result1,result2)


file.close()#關閉資源


#上下文管理器 with open as
with open("text.txt",'r',encoding="utf-8") as file:
    print(file.read())

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