python - 如何从 csv 或 txt 文件中删除标题?
问题描述
我选择了csv的特定列并将其转换为txt。
选定的列名是“id”(标题),我不知道如何从 txt 中删除该“id”。
这是我的代码..
import csv
with open('garosu_example.csv') as file:
reader = csv.reader(file)
input_file = "garosu_example.csv"
output_file = "garosu_example.txt"
id = ['id']
selected_column_index = []
with open(input_file, 'r', newline='') as csv_in_file:
with open(output_file, 'w', newline='/n') as csv_out_file:
freader = csv.reader(csv_in_file)
fwriter = csv.writer(csv_out_file)
header = next(freader)
for index_value in range(len(header)):
if header[index_value] in id:
selected_column_index.append(index_value)
print(id)
fwriter.writerow(id)
for row_list in freader:
row_list_output = []
for index_value in selected_column_index:
row_list_output.append(row_list[index_value])
print(row_list_output)
f.writer.writerow(row_list_output)
如何从 txt 文件中删除 'id'(header)?
如果我在 csv 中删除标题,则输出 txt 文件为空 T_T
解决方案
readlines
和的另一种方式writelines
:
with open('filename.csv') as f:
with open('no_header.csv', 'w') as f2:
f2.writelines(f2.readlines()[1:])
推荐阅读
- c# - 如何正确更改此代码?
- c++ - 为什么函数返回类型中不允许参数推导?
- java - 将 .pst 文件提取到 msg 但未获取 msg 文件的确切数量
- sql - 查询以列出与特定表关联的作业名称和步骤
- ruby-on-rails - Rails. Association of the same model with many parents
- scala - How to write integration tests depending on Druid?
- python - Function to translate input in one form to another
- swift - 定义布局以保存为图像 - Swift
- r - dplyr 在数据子集上
- node.js - how to connect to a server running on computer using computer's IP address?