Home > front end >  Prints to console. Now I want to print to CSV file
Prints to console. Now I want to print to CSV file

Time:10-20

I can read a text file with names and print in ascending order to console. I simply want to write the sorted names to a column in a CSV file. Can't I take the printed(file) and send to CSV? Thanks!

import csv
with open('/users/h/documents/pyprojects/boy-names.txt','r') as file:
    for file in sorted(file):
        print(file, end='')

#the following isn't working. 
with open('/users/h/documents/pyprojects/boy-names.csv', 'w', newline='') as csvFile:
    names = ['Column1']
    writer = csv.writer(names)
    print(file)

CodePudding user response:

You can do something like this:

import csv

with open('boy-names.txt', 'rt') as file, open('boy-names.csv', 'w', newline='') as csv_file:
    csv_writer = csv.writer(csv_file, quoting=csv.QUOTE_MINIMAL)
    csv_writer.writerow(['Column1'])
    for boy_name in sorted(file.readlines()):
        boy_name = boy_name.rstrip('\n')
        print(boy_name)
        csv_writer.writerow([boy_name])

CodePudding user response:

I believe this is adequately covered in the documentation.

The only tricky part is converting the lines from the file to a list of 1-element lists.

import csv
with open('/users/h/documents/pyprojects/boy-names.txt','r') as file:
    names = [[k.strip()] for k in sorted(file.readlines())]

with open('/users/h/documents/pyprojects/boy-names.csv', 'w', newline='') as csvFile:
    writer = csv.writer(csvFile)
    writer.writerow(['Column1'])
    writer.writerows(names)
  • Related