Search code examples
filecsvoutputcell

Write a string within a list to one cell in a CSV file. Python 2.7 Windows 7


Is it possible to write a string stored into a list into a .CSV file into one cell?

I have a folder with files and I want to write the file names onto a .csv file.

Folder with files:

    Data.txt
    Data2.txt
    Data3.txt

Here is my code:

    import csv
    import os
    index = -1 
    filename = []
    filelist = []
    filelist = os.listdir("dirname")

        f = csv.writer(open("output.csv", "ab"), delimiter=",", quotechar=" ", quoting=csv.QUOTE_MINIMAL)

    for file in filelist:
        if (len(filelist) + index) <0: 
            break
        filename = filelist[len(filelist)+index]
        index -= 1
        f.writerow(filename) 

Output I'm getting is one letter per cell in the .csv file:

      A B C D E F G H I       
    1 D a t a . t x t
    2 D a t a 2 . t x t
    3 D a t a 3 . t x t 

Desired output would be to have it all in 1 cell. There should be three rows on the csv file with strings "Data.txt" in cell A1, "Data2.txt" in cell B1, and "Data3.txt" in cell C1:

      A          B
    1 Data.txt
    2 Data2.txt
    3 Data3.txt

Is it possible to do this? Let me know if you need more information. I am currently using Python 2.7 on Windows 7.

Solution/Corrected Code:

    import csv
    import os
    index = -1 
    filename = []
    filelist = []
    filelist = os.listdir("dirname")

        f = csv.writer(open("output.csv", "ab"), delimiter=",", quotechar=" ", quoting=csv.QUOTE_MINIMAL)

    for file in filelist:
        if (len(filelist) + index) <0: 
            break
        filename = filelist[len(filelist)+index]
        index -= 1
        f.writerow([filename]) #Need to send in a list of strings without the ',' as a delimiter since writerow expects a tuple/list of strings.

Solution

  • You can do this:

    import csv
    import os
    
    filelist = os.listdir("dirname")  # Use a real directory
    f = csv.writer(open("output.csv", 'ab'), delimiter=",", quotechar=" ", quoting=csv.QUOTE_MINIMAL)
    for file_name in filelist:
        f.writerow([file_name])
    

    Writerow expects a sequence, for example a list of strings. You're giving it a single string which it is then iterating over causing you to see each letter of the string with a , between.