简体   繁体   中英

Exporting Python List to CSV in “column” format

right now I have Python 3 code that takes a column of data within a CSV file and then delimits the phrases in each cell into individual words based on spaces.

What I am trying to do now is export that data back into a CSV file in Column format so that it looks like this with each cell containing one word

Keyword
Lions
Tigers
Bears
Dog
Cats

Right now, my code exports the data to a CSV file but instead of coming in as a column format, it comes through in rows.

Keyword    Lions    Tigers     Bears     Dog    Cats

When I print my code in the interpreter, it comes through correctly in a column format but not when I export it! Here is my code

with open(b'C:\Users\j\Desktop\helloworld.csv', 'r') as datafile:
    data = []
    for row in datafile:
        data.extend(item.strip() for item in row.split())
with open('test.csv', 'w') as a_file:
    for result in data:
        result = ''.join(result)
        a_file.write(result + ',')
        print(result)

Does anyone have any ideas how to transpose the data? Thank you!

Since version 2.3, Python has had a builtin module for parsing csv data . Is there any reason you can't use that?

To give an answer, specifically on your code, though, here's what I notice:

    a_file.write(result + ',')
    print(result)

You're writing the data to the file appended with a comma, and printing it to the command line separately. So it shows up on the command line with one output on each line, but it's getting printed to the file as:

result1,result2,result3,result4...

All CSV files are slightly different, but commas generally delimit fields, while newlines delimit rows. You're getting exactly what you're outputting: one row with all of your values on it, in separate comma-delimited fields. Try this instead:

    a_file.write(result + '\n')

If you're in Python 3, then you can also use the print function:

    print(result, file=a_file)

You can use

"\n"

to make it written in the next row.

with open(b'C:\Users\j\Desktop\helloworld.csv', 'r') as datafile:
  data = []
  for row in datafile:
    data.extend(item.strip() for item in row.split())
with open('test.csv', 'w') as a_file:
  for result in data:
    result = ''.join(result)
    a_file.write(result + '\n')  <--
    print(result)

I don't know what result looks like, but I would say that you need to specify that you want to go to next line :

with open('test.csv', 'w') as a_file:
    for result in data:
        result = ''.join(result)
        a_file.write(result + ',') # if you want to keep the coma, or replace ',' by '\n'
        a_file.write("\n")
        print(result)

However, it's weird you don't get coma in your output, hope this helps anyway.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM