使用 Python 将制表符分隔的 txt 文件转换为 csv 文件 [英] Convert tab-delimited txt file into a csv file using Python

查看:49
本文介绍了使用 Python 将制表符分隔的 txt 文件转换为 csv 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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(' ') I get a list with each list item as a string with ' ' between each column. I was thinking I could just replace the ' ' with a comma but it won't treat the string within the list like string and allow me to use string.replace. Here is start of my code that still needs a way to parse the tab " ".

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('
')

for row in ec_file_list:       
    out_csv.writerow(row)

推荐答案

csv 支持制表符分隔的文件.将 delimiter 参数提供给 reader:

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 = '	')
out_csv = csv.writer(open(csv_file, 'wb'))

out_csv.writerows(in_txt)

这篇关于使用 Python 将制表符分隔的 txt 文件转换为 csv 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆