2

I want write csv (outfile) file from another csv file (infile). In infile csv data write like this OF0A0C,00,D0,0F11AFCB I want to write to outfile same asinfile but I get like this "\r \n 0,F,0,A,0,C,","0,0,","D,0,","0,F,1,1,A,F,C,B \r \n My code like this :

with open ("from_baryon.csv", "r") as inFile:
    with open (self.filename, "a") as outFile:
        for line in inFile:
            OutFile = csv.writer (outFile)
            OutFile.writerow (line)

After write I want to save every data in row to list like this Data = [[length_of_all_data],[length_data_row_1,datarow1],[length_data_row_2,datarow1datarow2],[length_data_row_3,datarow1datarow3]]

I confused to save the with list mode like that. Thankyou

1 Answer 1

2

Few issues -

  1. You should read the input csv file using csv module's csv.reader() , instead of iterating over its lines, since when you iterate over its lines, you get the line back as a string in the iteration - for line in inFile: , and then you are writing this line back using OutFile.writerow(line) , hence it writes each character into different columns.

  2. You do not need to create separate OutFile = csv.writer (outFile) for every line.

Example code -

with open ("from_baryon.csv", "r") as inFile:
    with open (self.filename, "a") as outFile:
        out_file = csv.writer (outFile)
        in_reader = csv.reader(inFile)
        for row in in_reader:
            out_file.writerow(row)

EDIT: For the second issue that is updated, you can create a list and a counter to keep track of the complete length. Example -

with open ("from_baryon.csv", "r") as inFile:
    with open (self.filename, "a") as outFile:
        out_file = csv.writer (outFile)
        in_reader = csv.reader(inFile)
        data = []
        lencount = 0
        for row in in_reader:
            out_file.writerow(row)
            tlen = len(''.join(row))
            data.append([tlen] + row)
            lencount += tlen
        data.insert(0,[lencount])
Sign up to request clarification or add additional context in comments.

7 Comments

Thank you, it solved my first problem. Do you have any idea for second problem?
What is the second problem? I didn't clearly understand. Are you looking for OutFile.writerows(data) ?
No, I just edit my post. My second problem is save to list
For second issue, you can explain with examples?
Example: In my outfile csv the data like this : "0F0A0C,00,0FF11C", "0F0A0C,00,0FF11D" I want save to list like this : [[32],[16,0F0A0C,00,0FF11C],[16,0F0A0C,00,0FF11C]] thank you.
|

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.