使用Python将制表符分隔的txt文件转换为csv文件

wil*_*bev 21 python csv text-files

所以我想将一个简单的制表符分隔文本文件转换为csv文件.如果我使用string.split('\n')将txt文件转换为字符串,我会得到一个列表,每个列表项都是一个字符串,每列之间有'\ t'.我以为我可以用逗号替换'\ t'但是它不会像字符串那样处理列表中的字符串并允许我使用string.replace.这是我的代码的开始,仍然需要一种方法来解析选项卡"\ t".

import csv
import sys

txt_file = r"mytxt.txt"
csv_file = r"mycsv.csv"

in_txt = open(txt_file, "r")
out_csv = csv.writer(open(csv_file, 'wb'))

file_string = in_txt.read()

file_list = file_string.split('\n')

for row in ec_file_list:       
    out_csv.writerow(row)
Run Code Online (Sandbox Code Playgroud)

agf*_*agf 44

csv支持制表符分隔文件.提供delimiter论据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)
Run Code Online (Sandbox Code Playgroud)

  • bikeshedding.脚本终止后,两个文件都会立即关闭.这是......立刻.+1. (3认同)