Convert txt to csv python script

后端 未结 4 930
栀梦
栀梦 2020-12-31 19:28

I have a .txt file with this inside - 2.9,Gardena CA

What I\'m trying to do is convert that text into a .csv (table) using a python script:

import c         


        
4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-31 20:30

    You need to split the line first.

    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)
    

提交回复
热议问题