如何用Python提取CSV每行数据并保存到对应TXT文件?
解决方案
方法一:使用原生csv模块
你可以同时打开所有目标TXT文件,遍历CSV的每一行数据,将对应列的内容逐行写入到各自的文件中。注意跳过表头行(第一行),避免把列名写入到结果文件里:
import csv # 打开所有目标文件,使用'w'模式清空原有内容并写入 with open('midvalues.csv', 'r', encoding='utf-8') as csv_file, \ open('id.txt', 'w', encoding='utf-8') as id_file, \ open('age.txt', 'w', encoding='utf-8') as age_file, \ open('number_of_pg.txt', 'w', encoding='utf-8') as pg_file, \ open('ratio.txt', 'w', encoding='utf-8') as ratio_file, \ open('Name.txt', 'w', encoding='utf-8') as name_file: csv_reader = csv.reader(csv_file) next(csv_reader) # 跳过表头行 for row in csv_reader: # 按列索引提取值,写入对应文件,每行末尾加换行符 id_file.write(row[0].strip() + '\n') age_file.write(row[1].strip() + '\n') pg_file.write(row[2].strip() + '\n') ratio_file.write(row[3].strip() + '\n') name_file.write(row[4].strip() + '\n')
方法二:使用pandas(更简洁,适配你之前的筛选工作流)
既然你已经用pandas处理过原始CSV,直接用pandas读取新生成的midvalues.csv,然后将每列单独导出为TXT文件即可:
import pandas as pd # 读取CSV文件 df = pd.read_csv('midvalues.csv') # 逐列导出到对应TXT文件,index=False去掉行号,header=False去掉列名 df['ID'].to_csv('id.txt', index=False, header=False) df['age'].to_csv('age.txt', index=False, header=False) df['number of played game'].to_csv('number_of_pg.txt', index=False, header=False) df['ratio'].to_csv('ratio.txt', index=False, header=False) df['Name'].to_csv('Name.txt', index=False, header=False)
两种方法都能实现需求:方法二更简洁,和你之前的操作习惯一致;方法一无需依赖pandas,适合轻量场景。
内容的提问来源于stack exchange,提问作者Damien
相关产品推荐
相关产品推荐

