23

所以我想将一个简单的制表符分隔的文本文件转换为 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)
4

3 回答 3

46

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)
于 2012-04-19T01:27:00.503 回答
1

为什么在使用csv模块读取文件时应该始终使用 'rb' 模式:

Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.

示例文件中的内容:任何旧垃圾,包括通过从数据库中提取 blob 或任何内容获得的控制字符,或CHAR在 Excel 公式中不明智地使用该函数,或...

>>> open('demo.txt', 'rb').read()
'h1\t"h2a\nh2b"\th3\r\nx1\t"x2a\r\nx2b"\tx3\r\ny1\ty2a\x1ay2b\ty3\r\n'

Python 在以文本模式读取文件时遵循 CP/M、MS-DOS 和 Windows:\r\n被识别为行分隔符并提供为\n,并且\x1aCtrl-Z 被识别为 END-OF-FILE 标记。

>>> open('demo.txt', 'r').read()
'h1\t"h2a\nh2b"\th3\nx1\t"x2a\nx2b"\tx3\ny1\ty2a' # WHOOPS

使用“rb”打开的文件的 csv 按预期工作:

>>> import csv
>>> list(csv.reader(open('demo.txt', 'rb'), delimiter='\t'))
[['h1', 'h2a\nh2b', 'h3'], ['x1', 'x2a\r\nx2b', 'x3'], ['y1', 'y2a\x1ay2b', 'y3']]

但文本模式不会:

>>> list(csv.reader(open('demo.txt', 'r'), delimiter='\t'))
[['h1', 'h2a\nh2b', 'h3'], ['x1', 'x2a\nx2b', 'x3'], ['y1', 'y2a']]
>>>
于 2012-04-19T03:16:43.283 回答
1

我就是这样做的

import csv

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)
于 2018-10-12T12:55:14.093 回答