繁体   English   中英

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

[英]Python Replace Strings based on column number in 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()

先感谢您!

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

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)

暂无
暂无

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

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