繁体   English   中英

使用python覆盖csv文件中的第一列和最后一列

[英]Overwrite the first and last column in csv file using python

我是使用CSV模块进行数据处理的新手。 而且我有输入文件 输入数据集 并使用此代码`

import csv
path1 = "C:\\Users\\apple\\Downloads\\Challenge\\raw\\charity.a.data"
csv_file_path =          "C:\\Users\\apple\\Downloads\\Challenge\\raw\\output.csv.bak"

with open(path1, 'r') as in_file:
    in_file.__next__()
    stripped = (line.strip() for line in in_file)
    lines = (line.split(":$%:") for line in stripped if line)
    with open(csv_file_path, 'w') as out_file:
        writer = csv.writer(out_file)
        writer.writerow(('id', 'donor_id','last_name','first_name','year','city','state','postal_code','gift_amount'))
    writer.writerows(lines)

` 当前输出文件

是否可以在csv文件的第一列和最后一列中删除(:)。 我希望输出像 预期输出(删除后:) 请帮我。

如果您只想在第一列和最后一列中消除“:”,则应该可以使用。 请记住,在阅读数据集之前,应将数据集tab (或逗号以外的其他内容)分开,因为正如我在问题中评论的那样,数据集中有逗号“,”。

path1 = '/path/input.csv'
path2 = '/path/output.csv'

with open(path1, 'r') as input, open(path2, 'w') as output:
file = iter(input.readlines())
output.write(next(file))

for row in file:
    output.write(row[1:][:-2] + '\n')

更新资料

因此,在提供您的代码之后,我做了一个小的更改以从初始文件开始进行整个过程。 想法是一样的。 您应该只排除每行的第一个和最后一个字符。 因此,您应该拥有line.strip()[1:][:-2]而不是line.strip()

import csv
path1 = "C:\\Users\\apple\\Downloads\\Challenge\\raw\\charity.a.data"
csv_file_path = "C:\\Users\\apple\\Downloads\\Challenge\\raw\\output.csv.bak"

with open(path1, 'r') as in_file:
    in_file.__next__()
    stripped = (line.strip()[1:][:-2] for line in in_file)
    lines = (line.split(":$%:") for line in stripped if line)
    with open(csv_file_path, 'w') as out_file:
        writer = csv.writer(out_file)
        writer.writerow(('id', 'donor_id','last_name','first_name','year','city','state','postal_code','gift_amount'))
        writer.writerows(lines)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM