1

I am trying to clean up the formating on a CSV file in order to import it into a database, and I'm using the following to edit it:

f1 = open('visit_summary.csv', 'r')
f2 = open('clinics.csv', 'w')

for line in f1:
    f2.write(line.replace('Calendar: ', ''))

f1.close()
f2.close()

This works fine if there is only 1 edit to make, however, I have to repeat this code 19 times in order to make all the changes required; opening and closing each file several times and having multiple placeholder fiels in order to use for intermediate steps ebtween the first and last edit). Is there a simpler way to do this? I tried adding more "f2.write(line.replace"... lines, however, this creates a final file with duplicated lines each of which has only 1 edit. I think I see my problem (I am writing each line multiple times with each edit), however, I cannot seem to find a solution. I am very new to python and am self teachign myself so any help, or direction to better resources would be appreciated.

3 Answers 3

2

There's no reason you can't do lots of things to the line before you write it:

with open('visit_summary.csv', 'r') as f1, open('clinics.csv', 'w') as f2:
    for line in f1:
        line = line.replace('Calendar: ', '')
        line = line.replace('Something else', '')
        f2.write(line)

(I also replaced open, close with the with statement)

1
  • Thanks! This helped a lot! I hadn't thought of it in that regard, still getting used to this language.
    – Owenlars2
    Commented May 9, 2013 at 18:53
1
f1 = open('visit_summary.csv', 'r')
f2 = open('clinics.csv', 'w')

for line in f1:
    f2.write(line.replace('Calendar: ', '').replace('String2', '').replace('String3', ''))

f1.close()
f2.close()

Will this work? Although I don't think its very "pythonic". In this case, you have to be careful about the ordering!

0
import csv
file1 = csv.DictReader(open('visit_summary.csv', 'r'))
output =[]
for line in file1:
    row= {}
    row['calender'] = line.replace('Calender:','')

row['string'] = line.replace('string','')
    output.append(row)

file = csv.DictReader(open('clinics.csv', 'w'))
fileWriter = csv.writer(file , delimiter=",",quotechar='"', quoting=csv.QUOTE_MINIMAL)

Header = ['something' , 'something']
fileWriter.writerow(Header)
for x in output:
temp = [x['something'],x['something']]
fileWriter.writerow(temp)
file.close()

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.