簡體   English   中英

如何將尾隨零添加到csv文件

[英]How to add trailing zeros to csv file

我努力了

num_columns = 982

def transform_row(row):
    #row = row.split('\n')  # split on new line
    row = row.split(',')  # split on commas
    row = [i.split() for i in row if i!='5']  # remove 5s
    row += ['0']*(num_columns - len(row))  # add 0s to end
    return ','.join(row) 
#and then apply this over the csv.

out = open('outfile.csv', 'w')
for row in open('dataset_TR1.csv'):
    out.write(transform_row(row))

本質上,我想從csv文件的每一行中刪除所有5,並用在982和983列之間的尾隨0代替丟失的長度。但是,使用http://www.filedropper.com/datasettr1中的數據文件,似乎只將所有內容都寫到一行,並且輸出不符合預期。

您必須分別處理逗號和換行符,以使其正確。

rows = "1,5,5,5,3\n2,5,5,5,9"
rows = rows.split('\n')
lines = []

for idx, row in enumerate(rows):
  row = row.split(',')  # split on commas
  row = [i for i in row if i!='5']  # remove 5s
  row += ['0']*(5 - len(row))  # add 0s to end
  row = ','.join(row)
  lines.append(row)


print(rows)
lines = '\n'.join(lines)
print(lines)

掃描並在\\ n上分割。 然后逐一掃描每行,進行替換,然后放回所有內容。

更好的方法是使用內置模塊csv

import csv
num_columns = 982

def transform_row(row):
    row = [column for column in row if column != '5']
    row += ['0'] * (num_columns - len(row))
    return row

fout = open('outfile.csv', 'w', newline='')
writer = csv.writer(fout)
fin = open('dataset_TR1.csv', 'r')
reader = csv.reader(fin)
for row in reader:
    writer.writerow(transform_row(row))
import csv

with open('dataset_TR1.csv', 'r') as f:
    reader = csv.reader(f)
    result = []
    for line in reader:
        print(len(line))
        remove_5s = [elem for elem in line if elem != '5']
        trailing_zeros = ['0'] * (len(line) - len(remove_5s))

        # if you want the zeros added to the end of the line
        # result.append(remove_5s + trailing_zeros)

        # or if you want the zeros added before the last element of the line
        result.append(remove_5s[:-1] + trailing_zeros + [remove_5s[-1]])

with open('output.csv', 'w') as f:
    writer = csv.writer(f)
    writer.writerows(result)

暫無
暫無

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

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