Python基于CSV中的列号替换字符串

2024-04-29 12:42:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要一些帮助来将一些字符串/字符替换到文件中。因为在我的Django数据库中,要么是整数,要么是字符串格式,我必须在导入之前首先自定义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- 

这是我使用的代码:

^{pr2}$

提前谢谢你!在


Tags: 文件csvdjango字符串数据库文件名格式公司
1条回答
网友
1楼 · 发布于 2024-04-29 12:42:53

对于像我这样的新手来说,这是我的解决方案。在

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)

相关问题 更多 >