繁体   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