Writing to different columns using python csv

Read the entire file and split it on whitespace. That should produce a a list with each row in it. Then write the entire row to the csv.

....
    for x in all_dir[:-1]:
        os.chdir(dirstart + '\\' + x)
        with open('Config.txt', "r") as working_file:
            data = working_file.read().split()
            writer.writerow(data)
        os.chdir(dirstart)

In your original, splitlines() gave you a list containing each line.

In [63]: working_file.readlines()
Out[63]: ['emily\n', 'randy\n', 'tom\n', 'eric\n', 'lisa']

So your original could be changed like this.

....
    for x in all_dir[:-1]:
        os.chdir(dirstart + '\\' + x)
        working_file = open('Config.txt', "r")
        commaseperated = working_file.readlines()
        #for i in commaseperated:
        writer.writerow(commaseperated)
        os.chdir(dirstart)
        working_file.close()

Notice that splitlines() retains the newline character at the end of each line. You probably do not want that in your csv file.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top