zoukankan      html  css  js  c++  java
  • Python:操作文件

    python操作文件库不需要安装其他module,文件操作类库是python语言自身支持的操作。

    判定文件是否存在:os.path.isfile(filePath)

    import os
    import sys
    
    if __name__=='__main__':
        filePath='d:\FTP\HUAWEI\1.txt'
        
        if os.path.isfile(filePath):
            #os.remove() will remove a file.
            #os.rmdir() will remove an empty directory.
            #shutil.rmtree() will delete a directory and all its contents.
            os.remove(filePath)
            print 'file has exists,was removed...'
            
        #if the file not exists will be created.
        fileObj=open(filePath,'w')
    
        # loop the list of dir
        for folder in os.listdir('D:\FTP\HUAWEI\20160513'):
            fileObj.write(folder+',')
    
        #if forget to close the file oject,the operate is not flush util the current process exit.
        fileObj.close()
    
        #read file
        fileReadObj=open('d:\FTP\HUAWEI\2.txt','r')
        fileWriterObj=open('d:\FTP\HUAWEI\3.txt','a')
        fileWriterObj.write('---------------------------------------------------------
    ')
        for line in fileReadObj.readlines():
            fileWriterObj.write('select '+ line+' id union all ')
        fileReadObj.close()
        fileWriterObj.close()

    参考资料:

    https://docs.python.org/3/library/os.html#os.remove

    http://www.pythonforbeginners.com/files/reading-and-writing-files-in-python

  • 相关阅读:
    音乐商店
    sort函数
    优先队列
    畅通工程 并查集,最小生成树,最短路径
    线段树(segment tree )
    bfs
    完全背包
    【Matlab】向图像域添加噪声/高斯/均匀/伽马/指数/椒盐
    【手帐】Bullet Journal教程
    【Matlab】取整函数:fix/round/floor/ceil
  • 原文地址:https://www.cnblogs.com/yy3b2007com/p/5721885.html
Copyright © 2011-2022 走看看