20190525:文件练习

    xiaoxiao2023-10-06  171

    #encoding=utf-8 """ 文件访问,提示输入数字 N 和文件 F, 然后显示文件 F 的前 N 行 """ import os def showFileRow(path,N,F): os.chdir(path) with open(os.path.join(path,F),"r") as fp: temp=fp.readlines() if N>len(temp): print(temp) else: for i in range(len(temp)): if i<N: print(temp[i]) print(showFileRow("e:\\murphy\\file",3,"result.py")) print(showFileRow("e:\\murphy\\file",10,"result.py")) #encoding=utf-8 """ 18、从命令行接受1个路径如:c:\a\b\c\1.py, 实现1个函数创建目录a\b\c,创建文件1.py,实现1个函数删除已创建的目录及文件 """ import os def createDirsFile(path): dirs=os.path.split(path)[0] file=os.path.split(path)[1] if not os.path.exists(dirs): os.makedirs(dirs) os.chdir(dirs) with open(file,"w") as fp: pass #print(createDirsFile("e:\\test1\\test\\a.py")) def removeDirsFile(path): dirs = os.path.split(path)[0] file = os.path.split(path)[1] os.chdir(dirs) if os.path.exists(file): print("file") os.remove(file) if os.path.exists(dirs): try: os.removedirs(dirs) except Exception as err: print(err) print(removeDirsFile("E:\\test1\\test\\1.txt"))

     

    最新回复(0)