Home > Software design >  Please HELP: Python Code to write csv file
Please HELP: Python Code to write csv file

Time:03-04

I am novice on python coding. I am having some issue to send data file into csv file. I am not sure why its not being sent the way its being printed. I couldn't manage to correct way looping. Can you please help me / suggest where did i miss in code? Image 1: shows how newline is being printed on right manner. However, when i use the for loop down its sending the file like image 2. What did I mistake and how to resolve to send exactly the same as showing into print data?

Thanks in advance!

Image:1 enter image description here

Image:2 enter image description here

image :3 enter image description here

CodePudding user response:

the variable 'newfile' in your first for-loop keeps getting overwritten each time your loop through it at line 52. Finally when you exit the loop and enter a new loop at line 72, you are iterating over the LAST assignment set on the 'newfile' variable (see https://stackoverflow.com/a/1816897/5198805) . You're also opening the same file multiple times and ovewriting it. You should open it once and then keep writing each line.

You should save the values in a temporary list

my_lines = []
#line 52
for row_in in range(len(..... stuff)):
    
    ... your code

    #line 69
    print(newfile)  # <-- this could be called processed_csv_line
    # new code you need to add here
    processed_csv_line = newfile
    my_lines = my_lines.append(processed_csv_line)


output_file = open("_output.csv","w")
csv_writer = csv.writer(output_file)
# line 72
for row_n in my_lines:
     csv_writer.writerow(row_n)

#remember to close file after writing
output_file.close()
  • Related