0

I need some help to replace some strings/characters into a file. Because in my Django DB i have either integers or strings formats i have to customize first the CSV before doing the import.

Therefore i need in entire columns 8 and 9 the character -0- to be replaced with 0. In the rest of the file i need -0-to be replaced with "null". The name of the file is sdn.csv and is located to my Desktop 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- 

This is the code i used:

    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()

Thank you in advance!

3
  • have you tried anything, like open the csv file yet or not? if you have can you provide the code ? Commented Sep 8, 2017 at 14:23
  • Hi @Bestasttung I am new to Python and don't know what to do :( i saw that there are other posts with panda, but i don't know how to customize them, so I need some help in order to understand how this can be done. Commented Sep 8, 2017 at 14:36
  • We're not here to do it for you. You're going to have to make an attempt and when you get stuck post the code and your issue(s). If you don't even try it what do you learn? You can always start with the built in python CSV API documentation: docs.python.org/2/library/csv.html Commented Sep 8, 2017 at 15:50

1 Answer 1

1

For other newbies like me, this was my solution.

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.