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())

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