Theme NexT works best with JavaScript enabled
utf8 注意跳过开头 3 个字节的 BOM
with codecs.open (filePath, 'r+' , 'utf-8' ) as f: content = f.read() f.seek(3 , 0 ) f.write(statisticStr + content)
delete os.remove() removes a file. os.rmdir() removes an empty directory. shutil.rmtree() deletes a directory and all its contents.
current path os.path.exists(test_file.txt)
是否存在 if not os.path.exists('./logs' ): os.makedirs('./logs' ) os.path.exists(test_file.txt) os.path.isfile("test-data" )
遍历 import osfor root, dirs, files in os.walk("." , topdown=True ): for name in files: print (os.path.join(root, name)) for name in dirs: print (os.path.join(root, name)) files.sort(key=lambda x: int (x.split('.' )[0 ][8 :]))
读写文件 L = ["Geeks\n" , "for\n" , "Geeks\n" ] file1 = open ('myfile.txt' , 'w' ) file1.writelines(L) file1.close() file1 = open ('myfile.txt' , 'r' ) Lines = file1.readlines() open ("file.txt" ).read().splitlines()['a' , 'b' , 'c' , 'd' ] count = 0 for line in Lines: print ("Line{}: {}" .format (count, line.strip()))
path split path = 'C:\\Program Files (x86)\\SPC\\Release\\Bin\\MeasureChartData\\P9.txt' os.path.split(path)
复制文件 try : shutil.copyfile(filePath, copy_path) except IOError as e: import traceback traceback.print_exc() errMsg = traceback.format_exc() log.info(f"Unable to copy file. {errMsg} " ) except : import traceback traceback.print_exc() errMsg = traceback.format_exc() log.info(f"Unexpected copy file error:{errMsg} " )
创建目录 import osdef mkdir (path ): path=path.strip() path=path.rstrip("\\" ) isExists=os.path.exists(path) if not isExists: ''' os.mkdir(path)与os.makedirs(path)的区别是,当父目录不存在的时候os.mkdir(path)不会创建,os.makedirs(path)则会创建父目录 ''' os.makedirs(path.decode('utf-8' )) print path+' 创建成功' return True else : print path+' 目录已存在' return False path=r"d:\\web天下\\" mkdir(path)
删除目录 os.rmdir(“dir ”) shutil.rmtree(“dir ”)