Python根据CSV中的列号替换字符串

时间:2017-09-08 13:38:54

标签: python csv

我需要一些帮助来将一些字符串/字符替换为文件。因为在我的Django DB中我有整数或字符串格式,我必须在导入之前首先自定义CSV。

因此,我需要在整个第8列和第9列中将字符-0-替换为0。在文件的其余部分,我需要将-0-替换为" null"。该文件的名称是sdn.csv,位于我的桌面C:\Users\icohen\Desktop\

Number  Name    B/I Program More Info   Vessel CallSign Vessel Type Vessel DWT (Deadweight tonnage) Gross Registered Tonnage    Vessel Flag Vessel Owner    DOB/AKA
36  AEROCARIBBEAN AIRLINES  -0-     CUBA    -0-     -0-     -0-     -0-     -0-     -0-     -0-     -0- 
173 ANGLO-CARIBBEAN CO., LTD.   -0-     CUBA    -0-     -0-     -0-     -0-     -0-     -0-     -0-     -0- 

这是我使用的代码:

    import csv

   file = '/Users/cohen/Desktop/sdn-2.csv'
    newstring = "null"
    newinteger = 0
    with open(file, 'r+') as f:
        for row in csv.reader(f):
           if row[7] =="-0-":
               row[7] = newinteger
           if row[8] == "-0-":
               row[8] = newinteger
    f.close()

提前谢谢!

1 个答案:

答案 0 :(得分:1)

对于像我这样的其他新手,这是我的解决方案。

import csv
newstring = "null"
newinteger = (0)
with open('/Users/cohen/Desktop/sdn-4 2.csv', 'r') as file1, open('/Users/cohen/Desktop/new_sdn.csv', 'w', newline='') as file2:
    reader = csv.reader(file1, delimiter=',')
    writer = csv.writer(file2, delimiter=',')

    for row in reader:
        replaced1 = row[7].replace('-0-', newstring)
        row[7]=replaced1
        replaced2 = row[8].replace('-0-', newinteger)
        row[8]=replaced2
        writer.writerow(row)