import csv with open('log.txt', 'r') as in_file: stripped = (line.strip() for line in in_file) lines = (line.split(",") for line in stripped if line) with open('log.csv', 'w') as out_file: writer = csv.writer(out_file) writer.writerow(('title', 'intro')) writer.writerows(lines)
Here is what the above code is Doing:
1. Open the log.txt file in read mode and assign it to the in_file variable.
2. Create a generator expression that strips the whitespace from each line in the file.
3. Create a generator expression that splits each line on the comma character.
4. Open the log.csv file in write mode and assign it to the out_file variable.
5. Create a csv.writer object and pass it the out_file variable.
6. Write the header row to the CSV file.
7. Write the data to the CSV file.