我是 python 的新手,只需要一点帮助。
我们有一个管道分隔的 CSV 文件,看起来像这样
DATE|20160101
ID | Name | Address | City | State | Zip | Phone | OPEID | IPEDS |
10 | A... | 210 W.. | Mo.. | AL... | '31.. | 334.. | '01023 | 10063 |
20 | B... | 240 N.. | Ne.. | Ut... | '21.. | 335.. | '01024 | 10064 |
Zip 和 OPEID 列的每个值开头都有撇号
因此我们希望创建一个新的 CSV 文件,其中从这两列的每个值中删除撇号。
新文件应该如下所示:
DATE|20160101
ID | Name | Address | City | State | Zip | Phone | OPEID | IPEDS |
10 | A... | 210 W.. | Mo.. | AL... | 31.. | 334.. | 01023 | 10063 |
20 | B... | 240 N.. | Ne.. | Ut... | 21.. | 335.. | 01024 | 10064 |
此代码适用于在不删除撇号的情况下复制数据
import os
import csv
file1 = "D:\CSV\File1.csv"
with open(file1, 'rb') as csvfile:
reader = csv.reader(csvfile, delimiter = '|')
path = "D:/CSV/New"
if not os.path.exists(path):
os.makedirs(path)
writer = csv.writer(open(path+"File2"+".csv", 'wb'), delimiter = '|')
for row in reader:
writer.writerow(row)
csvfile.close()
最佳答案
您可以使用 Pandas 非常高效地完成此操作——如果您的文件非常大,这会很好:
import pandas as pd
import sys
with open('t.txt') as infile:
title = next(infile)
infile.seek(0)
table = pd.read_csv(infile, '|', header=1, dtype=str)
table.rename(columns={'Unnamed: 9':''}, inplace=True)
table[' Zip '] = table[' Zip '].str.replace("'", "")
table[' OPEID '] = table[' OPEID '].str.replace("'", "")
sys.stdout.write(title)
table.to_csv(sys.stdout, '|', index=False)
关于python - 使用python更改CSV文件中列的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39165533/