import os,stat
#打开不存在的文件
file1 = open("./Anna.txt","w",encoding='utf-8')
file1.close()
file1 = open("./Anna1.txt","a",encoding='utf-8')
file1.close()
file1 = open("./Anna2.txt","a+",encoding='utf-8')
file1.close()
file1 = open("./Anna3.txt","w+",encoding='utf-8')
file1.close()
#总结:
#创建文件有4种方式,w,w+,a,a+
#使用w和w+方式新建文件如果文件存在则会覆盖原所有内容
#使用a,a+如果文件存在不会覆盖内容
#open()函数打开文件后必须要使用close()关闭,如果文件不存在,新建文件不需要关闭该文件
file1 = open("./Anna4.txt","w",encoding='utf-8')
file1.writelines("第一行
第二行")
file1.close()
file1 = open("./Anna4.txt","r+",encoding='utf-8')
print(file1.read(3)) #读取指定的值
file1.seek(0,0)#指针偏移量,0 文件开头,1 当前位置,2 文件末尾
print(file1.readline())#一行一行的读取
print("当前指针的位置",file1.tell())
file1.seek(0,0)
print(file1.readlines())#读取文件的所有内容,返回到一个列表中
file1.seek(0,0)
print(file1.readlines()[1])#读取某一行数据
file1.close()
#with方法,不需要关闭文件
with open("./Anna4.txt","r",encoding='utf-8') as file2:
res = file2.readlines()
print(res)
#os模块
try:
os.mkdir(r"C:UsersAdministratorDesktopAnna6")
except FileExistsError as e:
print("[WinError 183] 当文件已存在时,无法创建该文件",e)
path1 = 'C:\UsersAdministratorDesktopAnna6'
if os.path.exists(path1):
os.renames('C:\UsersAdministratorDesktopAnna6','C:\UsersAdministratorDesktopAnna7')
print("has rename the path")
os.rmdir('C:\UsersAdministratorDesktopAnna7') #删除非空目录
print("has deled the rename file")
else:
print("path not exist")
res = os.access("./Anna4.txt",os.F_OK)#文件是否存在
print(res)
print(os.access("./Anna4.txt",os.R_OK))#可读
print(os.access("./Anna4.txt",os.W_OK))#可写
print(os.access("./Anna4.txt",os.X_OK))#可执行
print('目录和文件拼接路径:',os.path.join(r':UsersAdministratorDesktopGaara.txt','Narodo.txt'))
print(os.path.split(r':UsersAdministratorDesktopGaara.txt'),type(os.path.split(r':UsersAdministratorDesktopGaara.txt')))
os.chmod(r'C:UsersAdministratorDesktopGaara.txt',stat.S_IREAD)
# stat.S_ISUID: Set user ID on execution. 不常用
# stat.S_ISGID: Set group ID on execution. 不常用
# stat.S_ENFMT: Record locking enforced. 不常用
# stat.S_ISVTX: Save text image after execution. 在执行之后保存文字和图片
# stat.S_IREAD: Read by owner. 对于拥有者读的权限
# stat.S_IWRITE: Write by owner. 对于拥有者写的权限
# stat.S_IEXEC: Execute by owner. 对于拥有者执行的权限
# stat.S_IRWXU: Read, write, and execute by owner. 对于拥有者读写执行的权限
# stat.S_IRUSR: Read by owner. 对于拥有者读的权限
# stat.S_IWUSR: Write by owner. 对于拥有者写的权限
# stat.S_IXUSR: Execute by owner. 对于拥有者执行的权限
# stat.S_IRWXG: Read, write, and execute by group. 对于同组的人读写执行的权限
# stat.S_IRGRP: Read by group. 对于同组读的权限
# stat.S_IWGRP: Write by group. 对于同组写的权限
# stat.S_IXGRP: Execute by group. 对于同组执行的权限
# stat.S_IRWXO: Read, write, and execute by others. 对于其他组读写执行的权限
# stat.S_IROTH: Read by others. 对于其他组读的权限
# stat.S_IWOTH: Write by others. 对于其他组写的权限
# stat.S_IXOTH: Execute by others. 对于其他组执行的权限