打开.csv文件编辑一个字段,写回.csv文件

时间:2018-05-16 20:31:05

标签: python csv formatting

所以我有一个.csv文件,其中包含姓名,lat,lon和电话号码;用逗号分隔。我需要打开文件,将电话号码编辑成更清晰的格式,然后将其写回文件。

有一个很好的解决方案来编辑​​电话号码Here

不确定解决此问题的最佳方法。任何帮助是极大的赞赏。谢谢。

import csv

def phone_format(n):
    return format(int(n[:-1]), ",").replace(",", "-") +n[-1]

with open('sample.csv', 'rU') as csvfile:
    spotreader = csv.reader(csvfile)
    spotwriter = csv.writer(csvfile)
    for row in spotreader:
        spotwriter.writerow([0] + phone_format(spotreader[1]))

这不起作用。不确定如何得到我想要的东西。

我的csv文件示例

Jason Schow,,5016098648
Dena VanGorder,,6074621816
Lindsey McNabb,3066533971,3066505001
Jeff Wozniak,3066531566,3069420647
Victoria Norton,3067692840,3067697062
Benjie Butikofer,3067692107,3067697108
Jessica Duede,,3062813158
Pete Vogeh,3063776261,3069890349
Melissa Kwasney,,3069412583

我正在寻找的.csv文件的输出类型:

Jason Schow,,501-609-8648
Dena VanGorder,,607-462-1816
Lindsey McNabb,306-653-3971,306-650-5001
Jeff Wozniak,306-653-1566,306-942-0647
Victoria Norton,306-769-2840,306-769-7062
Benjie Butikofer,306-769-2107,306-769-7108
Jessica Duede,,306-281-3158
Pete Vogeh,306-377-6261,306-989-0349
Melissa Kwasney,,306-941-2583

2 个答案:

答案 0 :(得分:1)

你不应该在行上格式化,而不是使用spotreader吗?这对我从.csv文件中读取它很好。我添加了一个忽略空字符串的检查。由于您没有在写入模式下打开文件,因此无法使用spotwriter。 'rU'仅为读模式。你想要做的是制作一个全新的.csv文件,并将输出写在那里:

import csv

def phone_format(n):
    return format(int(n[:-1]), ",").replace(",", "-") +n[-1]

with open('sample.csv', 'rU') as csvfile:
    with open('sampleOutput.csv', 'w') as csvfile2:
        spotreader = csv.reader(csvfile)
        spotwriter = csv.writer(csvfile2)
        for row in spotreader:
            if row[1] != '':
                spotwriter.writerow([row[0], phone_format(row[1]), row[2]])
            else:
                spotwriter.writerow([row[0], row[1], row[2]])

输入是您的.csv文件。

输出:

Jason Schow,,5016098648
Dena VanGorder,,6074621816
Lindsey McNabb,306-653-3971,3066505001
Jeff Wozniak,306-653-1566,3069420647
Victoria Norton,306-769-2840,3067697062
Benjie Butikofer,306-769-2107,3067697108
Jessica Duede,,3062813158
Pete Vogeh,306-377-6261,3069890349
Melissa Kwasney,,3069412583

这假设你只想编辑第一个电话号码,如果你想编辑第二个电话号码,你还需要做一些额外的编程。

答案 1 :(得分:0)

弄清楚了。我在另一篇stackoverflow文章中偶然发现了这一点。 Article Here

更正后的代码如下。再次感谢所有的帮助和建议。

import csv

def phone_format(n):
    return format(int(n[:-1]), ",").replace(",", "-") +n[-1]

with open('sample.csv', 'rU') as csvfile:
    with open('sampleOutput.csv', 'w', newline='') as csvfile2:
        spotreader = csv.reader(csvfile)
        spotwriter = csv.writer(csvfile2)
        for row in spotreader:
            if row[1] != '' and row[2] != '':
                spotwriter.writerow([row[0], phone_format(row[1]), phone_format(row[2])])
            elif row[1] != '' and row[2] == '':
                spotwriter.writerow([row[0], phone_format(row[1]), (row[2])])
            elif row[1] == '' and row[2] != '' :
                spotwriter.writerow([row[0], (row[1]), phone_format(row[2])])