Python:操作文件
生活随笔
收集整理的這篇文章主要介紹了
Python:操作文件
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
python操作文件庫不需要安裝其他module,文件操作類庫是python語言自身支持的操作。
判定文件是否存在:os.path.isfile(filePath)
?
import os import sysif __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 dirfor 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 filefileReadObj=open('d:\\FTP\\HUAWEI\\2.txt','r')fileWriterObj=open('d:\\FTP\\HUAWEI\\3.txt','a')fileWriterObj.write('---------------------------------------------------------\r\n')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
轉載于:https://www.cnblogs.com/yy3b2007com/p/5721885.html
總結
以上是生活随笔為你收集整理的Python:操作文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 关于排版中经常见的问题的解决方法
- 下一篇: 如何下载图片新闻并将其写入文件