0

I have a csv file that I need to change the date value in each row. The date to be changed appears in the exact same column in each row of the csv.

import csv

firstfile  = open('example.csv',"r")
firstReader = csv.reader(firstfile, delimiter='|')
firstData = list(firstReader)

DateToChange = firstData[1][25]
ChangedDate = '2018-09-30'

for row in firstReader:
        for column in row:
            print(column)
            if column==DateToChange:
                  #Change the date

    outputFile = open("output.csv","w")
    outputFile.writelines(firstfile)
    outputFile.close()

I am trying to grab and store a date already in the csv and change it using a for loop, then output the original file with the changed dates. However, the code above doesn't seem to do anything at all. I am newer to Python so I might not be understanding how to use a for loop correctly.

Any help at all is greatly appreciated!

4
  • Can you post sample input data Commented Nov 26, 2018 at 17:30
  • This seems like a simple find and replace, so you can just use a text editor or Excel. Commented Nov 26, 2018 at 17:32
  • DETAIL|2507|2018-10-13|7|TESTUSER23|User|Test|J|AP|10001|||||||||JSHDKF02SD45FSD|11315|BF|USD|UNITED STATES|2018-10-04|2018-09-07|2018-09-30|September 2018|Y|N|N| Above is a same row I am importing @Tomothy32 The problem is that the date I am trying to replace could appear multiple times outside the column I am trying to replace Commented Nov 26, 2018 at 17:36
  • Still feel like this can be accomplished in Excel. Just select an entire column, then do find and replace and it should only operate in that column. Also, in a text editor, you can find and replace in a certain column using regex. Commented Nov 26, 2018 at 17:39

2 Answers 2

1

When you call list(firstReader), you read all of the CSV data in to the firstData list. When you then, later, call for row in firstReader:, the firstReader is already exhausted, so nothing will be looped. Instead, try changing it to for row in firstData:.

Also, when you are trying to write to file, you are trying to write firstFile into the file, rather than the altered row. I'll leave you to figure out how to update the date in the row, but after that you'll need to give the file a string to write. That string should be ', '.join(row), so outputFile.write(', '.join(row)).

Finally, you should open your output file once, not each time in the loop. Move the open call to above your loop, and the close call to after your loop. Then when you have a moment, search google for 'python context manager open file' for a better way to manage the open file.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! This helped a lot and gave me a good place to start
Is there any way to "re delimiter"? My csv has pipe delimiters because commas appear naturally in the data. I have my data changed and writing to a .txt but I would like to make it seperated by "|" instead of commas.
Of course. The delimiter is just set by the ','.join() part - change that comma to a pipe and you're away
0

you could use pandas and numpy. Here I create a dataframe from scratch but you could load it directly from a .csv:

import pandas as pd
import numpy as np

date_df = pd.DataFrame(
    {'col1' : ['12', '14', '14', '3412', '2'],
     'col2' : ['2018-09-30', '2018-09-14', '2018-09-01', '2018-09-30', '2018-12-01']
    })

date_to_change = '2018-09-30'
replacement_date = '2018-10-01'

date_df['col2'] = np.where(date_df['col2'] == date_to_change, replacement_date, date_df['col2'])

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.