Python根据CSV中的列号替换字符串
我需要一些帮助来将一些字符串/字符替换到文件中。因为在Django DB中,我有整数或字符串格式,所以在导入之前,我必须首先自定义CSV 因此,我需要在整个第8列和第9列中将字符Python根据CSV中的列号替换字符串,python,csv,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 (Dead
-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)
您是否尝试过任何方法,比如打开csv文件?如果你有,你能提供代码吗?Hi@bestasttong我是Python新手,不知道该怎么做:(我看到有其他关于panda的帖子,但我不知道如何自定义它们,所以我需要一些帮助来了解如何做到这一点。我们不是来帮你的。你必须尝试一下,当你被卡住时,发布代码和你的问题。)。如果你不尝试,你会学到什么?你可以从内置的python CSV API文档开始:谢谢!我发布了我的代码