Convert txt to csv python script

后端 未结 4 912
栀梦
栀梦 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:17
    import pandas as pd
    df = pd.read_fwf('log.txt')
    df.to_csv('log.csv')
    
    0 讨论(0)
  • 2020-12-31 20:22

    I suposse this is the output you need:

    title,intro,tagline

    2.9,Gardena,CA

    It can be done with this changes to your code:

    import csv
    import itertools
    
    with open('log.txt', 'r') as in_file:
        lines = in_file.read().splitlines()
        stripped = [line.replace(","," ").split() for line in lines]
        grouped = itertools.izip(*[stripped]*1)
        with open('log.csv', 'w') as out_file:
            writer = csv.writer(out_file)
            writer.writerow(('title', 'intro', 'tagline'))
            for group in grouped:
                writer.writerows(group)
    
    0 讨论(0)
  • 2020-12-31 20:28

    This is how I do it:

     with open(txtfile, 'r') as infile, open(csvfile, 'w') as outfile:
            stripped = (line.strip() for line in infile)
            lines = (line.split(",") for line in stripped if line)
            writer = csv.writer(outfile)
            writer.writerows(lines)
    

    Hope it helps!

    0 讨论(0)
  • 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)
    
    0 讨论(0)
提交回复
热议问题