Convert tab-delimited txt file into a csv file using Python

后端 未结 3 1671
臣服心动
臣服心动 2020-11-30 02:51

So I want to convert a simple tab delimited text file into a csv file. If I convert the txt file into a string using string.split(\'\\n\') I get a list with each list item a

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-30 03:05

    csv supports tab delimited files. Supply the delimiter argument to reader:

    import csv
    
    txt_file = r"mytxt.txt"
    csv_file = r"mycsv.csv"
    
    # use 'with' if the program isn't going to immediately terminate
    # so you don't leave files open
    # the 'b' is necessary on Windows
    # it prevents \x1a, Ctrl-z, from ending the stream prematurely
    # and also stops Python converting to / from different line terminators
    # On other platforms, it has no effect
    in_txt = csv.reader(open(txt_file, "rb"), delimiter = '\t')
    out_csv = csv.writer(open(csv_file, 'wb'))
    
    out_csv.writerows(in_txt)
    

提交回复
热议问题