当前位置:   article > 正文

python批量读取csv并提取其中多行生成新csv_python编写程序,要求读取一个包含多行多段文字的文本文档,然后重新生成新文

python编写程序,要求读取一个包含多行多段文字的文本文档,然后重新生成新文

同学有大量csv文件,要我帮忙提取每个csv中‘type’字段为‘O3’的整一行数据

于是,上代码!

  1. import csv
  2. import os
  3. import pandas as pd
  4. import json
  5. # 设置显示的最大列、宽等参数,消掉打印不完全中间的省略号
  6. # pd.set_option('display.max_columns', 1000)
  7. pd.set_option('display.width', 1000)
  8. # pd.set_option('display.max_colwidth', 1000)
  9. # pd.set_option('display.height', 1000)
  10. # 显示所有列
  11. pd.set_option('display.max_columns', None)
  12. # 显示所有行
  13. pd.set_option('display.max_rows', None)
  14. dict = []
  15. file_path = 'file' # 设置文件路径
  16. # 建立空list
  17. code_list = []
  18. for root, dirs, files in os.walk(file_path):
  19. # print(root)
  20. # print(dirs)
  21. # print(files)
  22. for filename in files:
  23. code_list.append(filename)
  24. list_number = len(code_list)
  25. index = 0
  26. for k in code_list:
  27. if index < int(list_number):
  28. file_name = 'file/' + code_list[index]
  29. index += 1
  30. with open(file_name, 'r', encoding="utf-8") as csvfile:
  31. reader = csv.DictReader(csvfile)
  32. for row in reader:
  33. if row['type'] == 'O3':
  34. # j = json.dumps(row, ensure_ascii=False)
  35. # print(j)
  36. # with open('test_data.json', 'a') as json_file:
  37. # json_file.write(j)
  38. dict.append(row)
  39. print(row)
  40. pd.DataFrame(dict).to_csv('2021.csv')
'
运行

利用pandas的DataFrame.to_csv方法,记得用的输入参数是字典格式而并非json

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

闽ICP备14008679号