Python Forum

Full Version: How to manipulate csv 2
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
hi,

I have a csv file (attached the file with the name professional_data.csv)
in the attached format has few columns KeyXID,Structural Engineer,Architect,Contractor,Landscape Engineer,Vaastu Consultant
.. how can i manipulate csv using python so that i can take first 50 characters from every columns and write them to new csv file

i have written a code
import csv

filename = "options_book.csv"
OUT_FILE = "options_book_50_char.csv"

with open(filename, "r") as csvfile:
    csv = csv.DictReader(csvfile)
    for row in csv:
        data = row["KeyXID"][:50], row[" Structural Engineer"][:50], row[" Architect"][0:50], row[" Contractor"][:50], row["Landscape Engineer"][:50], row["Vaastu Consultant"][:50]
        f_line = list(data)

              
with open("./"+OUT_FILE, "w") as csvfile:
    csvfile = csv.writer(csvfile, delimiter=",")
    csvfile.writerow("")
    for i in range(0, len(f_line)):
        csvfile.writerow(f_line[i])
this works partially. it is printing what i am looking for but not writing. and there is an error when i run the code which is :
Error:
DictReader' object has no attribute 'writer'
i am reading csv reading and writing but didn't understand how to remove that error. if someone can guide me in this would be helpful.
the problem is that on line#7 you overwrite csv name and it no longer refer to csv module, but to csv.DictReader object. Choose different name for the reader, e.g. csv_rdr
However, the result will not be what you expect. I will leave to you to make necessary fix.
hi,

thank you so much, i made some changes and it is working fine now..

below is the code

import csv

filename = "professional_data.csv"
OUT_FILE = "options_book_50_char.csv"

final_data = []
with open(filename, "r") as csvfile:
    csv_rdr = csv.DictReader(csvfile)
    for row in csv_rdr:
        data = row["KeyXID"][:50], row[" Structural Engineer"][:50], row[" Architect"][0:50], row[" Contractor"][:50], row["Landscape Engineer"][:50], row["Vaastu Consultant"][:50]
        final_data.append(data)
              
with open("./"+OUT_FILE, "w") as csvfile:
    csvfile = csv.writer(csvfile, delimiter=",")
    csvfile.writerow("")
    for i in range(0, len(final_data)):
        csvfile.writerow(final_data[i])
Never use constructs like
for i in range(0, len(final_data))
see https://python-forum.io/Thread-Basic-Nev...n-sequence

Just FYI, below is concise version of the code

import csv

filename = "professional_data.csv"
OUT_FILE = "options_book_50_char.csv"

with open(filename, "r") as infile, open(OUT_FILE, "w") as outfile:
    csv_rdr = csv.reader(infile)
    csv_wrtr = csv.writer(outfile)
    for row in csv_rdr:
        csv_wrtr.writerow(value[:50] for value in row)
Thank you so much sir, i'll make sure that