当前位置:   article > 正文

Python Write 写文件_pyspark write 怎么写成一个文件

pyspark write 怎么写成一个文件

Python 写文件是常用的操作,这里整理一下;

1. write txt

  1. namelist=[]
  2. namelist.append(input.item())
  3. with open("namelist.txt", "w",encoding="utf-8") as f:
  4. for i in namelist:
  5. f.write(str(i)+'\n')

2 .write csv 表格;

  1. fileNameID =0
  2. def write_csv(fileNameID,filename,file_md5):
  3. # 表头
  4. header = ["序号", "名称", "MD5"]
  5. areas =[str(fileNameID) ,str(filename), str(file_md5)]
  6. with open('file_md5.csv', mode='a', encoding='utf_8_sig',newline="") as file_obj:
  7. # 1:创建writer对象
  8. writer = csv.writer(file_obj)
  9. # 2:写表头
  10. if fileNameID==0:
  11. writer.writerow(header)
  12. writer.writerow(areas)

例:计算目录下所有文件的MD5值

  1. #计算目录下所有文件的MD5
  2. # coding:utf-8
  3. import os
  4. import hashlib
  5. import csv
  6. RootDir = './Release'
  7. fileNameID =0
  8. def write_csv(fileNameID,filename,file_md5):
  9. # 表头
  10. header = ["序号", "名称", "MD5"]
  11. # uheader = []
  12. # for i in header:
  13. # uheader.append(i.encode("utf-8"))
  14. areas =[str(fileNameID) ,str(filename), str(file_md5)]
  15. with open('file_md5.csv', mode='a', encoding='utf_8_sig',newline="") as file_obj:
  16. # 1:创建writer对象
  17. writer = csv.writer(file_obj)
  18. # 2:写表头
  19. if fileNameID==0:
  20. writer.writerow(header)
  21. writer.writerow(areas)
  22. def md5_test(dir):
  23. global fileNameID
  24. list_item = os.listdir(dir)
  25. for f in list_item:
  26. path = os.path.join(dir,f)
  27. if os.path.isdir(path):
  28. md5_test(path)
  29. #print(tuple_result[0],tuple_result[1])
  30. else:
  31. if path.endswith('.dll') or path.endswith('.exe'):
  32. with open(path,'rb') as fp:
  33. data = fp.read()
  34. file_md5 = hashlib.md5(data).hexdigest()
  35. #print(fileNameID,',',f,',',file_md5)
  36. write_csv(fileNameID,f,file_md5)
  37. # else:
  38. # print(fileNameID, ',', f, ',', file_md5)
  39. fileNameID += 1
  40. #return path,file_md5
  41. if __name__ == '__main__':
  42. md5_test(RootDir)

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/43945
推荐阅读
相关标签
  

闽ICP备14008679号