簡體   English   中英

將 csv 中的某些列附加到另一個 csv 文件不會拆分每一行

[英]appending certain columns in csv to another csv file is not spilting each row

我發現了一個小的 python 代碼來創建一個新的 csv 文件,其中包含來自另一個 csv 文件的選定列它幾乎可以正常工作,只是沒有在新行上顯示每一行。 它目前在同一條線上。

這是代碼:

import csv

file_name =  'input.csv'
output_file = 'output.csv'
csv_file = open(file_name, 'r')
## note that the index of the year column is excluded
column_indices = [0,1,25,23,5,6,9,27,28,31,33,34,37,72,73,76,105,106,109,45,46,49]
with open(output_file, 'w') as fh:
    reader = csv.reader(csv_file, delimiter=',')
    for row in reader:
       tmp_row = []
       for col_inx in column_indices:
           tmp_row.append(row[col_inx])
       fh.write(','.join(tmp_row))

在最后一列之后,我需要它來創建一個新行,而目前所有內容都在同一行上

要么使用csv.writer並使用.writerow或寫換行符。 一種選擇是將printfile=選項一起使用:

# replace this
# fh.write(','.join(tmp_row))
# with any of these:
print(*tmp_row, sep=",", file=fh) # default is end="\n" so you get rows
fh.writelines([','.join(tmp_row)])
fh.write(','.join(tmp_row) + '\n')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM