# # 文件读取(r表示只读,w表示只写,a表示添加,b表示二进制格式,+表示以读写模式打开,不能单独使用,需要与其他模式一起,如a+)
# file=open('test.txt','rb')
# print(file.readlines())
# file.close()
# # 文件写入
# file=open('test.txt','a')
# file.write('This is the first line\n') # write a string to a file with a '\n'.
# file.close()
# # 文件写入
# file=open('test.txt','a')
# file.write('This is the first line\n') # write a string to a file with a '\n'.
# file.close()
# # 文件复制
# src_file=open('logo.png','rb')
# target_file=open('copylogo.png','wb')
# target_file.write(src_file.read())
# target_file.close()
# src_file.close()
# #with语句可以自动关闭文件,open('logo.png','rb')称为上下文管理器,自动调用__enter__、__exit__方法
# with open('logo.png','rb') as src_file:
# with open('copy21logo.png','wb') as target_file:
# target_file.write(src_file.read())
# # 自己设计上下文管理器,实现__enter__、__exit__方法
# # 也可以使用类似的代码在其他文件模式中实现ContextManager。
# # # 创建一个ContextManager实例,并将其作为参数给ContextManager()方法,然后在调用它时调用它的with语法中的ContextManager类型。 with语法中的ContextManager实现必须自动调用其__enter__和__exit__方法,而不必手动调用。
# class myContextManager(object): # 这里使用文档的方式定义ContextManager类型。
# def __enter__(self):
# print('enter方法被调用执行了')
# return self
# def __exit__(self,exc_type,exc_val,exc_tb):
# print('exit方法被调用执行了')
# def show(self):
# print('show方法被调用执行了')
# with myContextManager() as cm: # cm = ContextManager() instance, as needed.
# cm.show() # 调用cm的show方法。这里cm是__enter__方法的返回值,即myContextManager的实例
# os模块是与操作系统相关的模块
# import os
# '-------'
# print(os.getcwd()) # get current working directory
# os.system('calc.exe')
# 直接调用可执行文件
# os.system('C:\\ProgramFiles(x86)\\Tencent\\WeMeet\\wemeetapp.exe') # 可执行文件名必须是小写
# '---列出指定目录下的所有文件----'
# lst=os.listdir(os.getcwd())
# for filename in lst:
# if filename.endswith('.py'):
# print(filename)
# '-------'
# os.mkdir('newdir') # create a directory
# os.removedirs('newdir') # remove a directory
# os.makedirs('newdir/newdir2') # create a directory tree
# os.chdir('newdir') # change directory
# print(os.getcwd()) # get current working directory
# os.removedirs('newdir/newdir2') # remove a directory tree
# os.path模块是与操作系统相关的模块
import os.path
print(os.path.abspath('test.txt'))
print(os.path.exists('test.txt')) # test if a file exists
print(os.path.isfile('test.txt')) # test if a file path points to a file
print(os.path.isdir('test.txt')) # test if a file path points to a directory
print(os.path.split('\\home\\user\\test.txt')) # get the directory path and file name
print(os.path.splitext('\\home\\user\\test.txt')) # get the directory path, file name and extension
print(os.path.getmtime('test.txt')) # get the last modified time of a file
print(os.path.getsize('test.txt')) # get the size of a file in bytes
print(os.path.join('\\home\\user\\test', '.txt'))
print(os.path.basename('\\home\\user\\test.txt')) # get the filename without the directory path
马士兵python学习杨淑娟老师第十一章--文件读写
最新推荐文章于 2024-06-19 19:57:02 发布