[英]How to read a column without header from csv and save the output in a txt file using Python?
I have a file "TAB.csv" with many columns.我有一个包含许多列的文件“TAB.csv”。 I would like to choose one column without header (index of that column is 3) from CSV file.
我想从 CSV 文件中选择一列没有标题(该列的索引为 3)。 Then create a new text file "NEW.txt" and write there that column (without header).
然后创建一个新的文本文件“NEW.txt”并在那里写入该列(不带标题)。
Below code reads that column but with the header.下面的代码读取该列,但带有标题。 How to omit the header and save that column in a new text file?
如何省略标题并将该列保存在新的文本文件中?
import csv
with open('TAB.csv','rb') as f:
reader = csv.reader(f)
for row in reader:
print row[3]
This is the solution @tmrlvi was talking: it skips the first row (header) via next function:这是@tmrlvi 所说的解决方案:它通过下一个函数跳过第一行(标题):
import csv
with open('TAB.csv','rb') as input_file:
reader = csv.reader(input_file)
output_file = open('output.csv','w')
next(reader, None)
for row in reader:
row_str = row[3]
output_file.write(row_str + '\n')
output_file.close()
Try this:尝试这个:
import csv
with open('TAB.csv', 'rb') as f, open('out.txt', 'wb') as g:
reader = csv.reader(f)
next(reader) # skip header
g.writelines(row[3] + '\n' for row in reader)
enumerate
is a nice function that returns a tuple. enumerate
是一个很好的函数,它返回一个元组。 It enables to to view the index while running over an iterator.它可以在运行迭代器时查看索引。
import csv
with open('NEW.txt','wb') as outfile:
with open('TAB.csv','rb') as f:
reader = csv.reader(f)
for index, row in enumerate(reader):
if index > 0:
outfile.write(row[3])
outfile.write("\n")
Another solution would be to read one line from the file (in order to skip the header).另一种解决方案是从文件中读取一行(以跳过标题)。
It's an old question but I would like to add my answer about Pandas library, I would like to say.这是一个老问题,但我想补充一下关于 Pandas 库的答案,我想说。 It's better to use Pandas library for such tasks instead of writing your own code.
最好将 Pandas 库用于此类任务,而不是编写自己的代码。 And the simple code with Pandas will be like :
Pandas 的简单代码如下:
import pandas as pd
reader = pd.read_csv('TAB.csv', header = None)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.