【发布时间】:2017-04-24 12:37:29
【问题描述】:
我想在不丢失列对齐的情况下使用 python 将多个 csv 文件转换为 txt。
一个 csv 文件的示例,以逗号分隔,没有空格或制表符,如下所示:
"Products" "Technologies" Region1 Region2 Region3
Prod1 Tech1 16 0 12
Prod2 Tech2 0 12 22
Prod3 Tech3 22 0 36
但使用我的脚本,我最终得到以下结果:
"Products" "Technologies" Region1 Region2 Region3
Prod1 Tech1 16 0 12
Prod2 Tech2 0 12 22
Prod3 Tech3 22 0 36
分隔符的选择是任意的。考虑到带有 csv 文件的表的尺寸会有所不同,并且列标题的长度会有所不同,是否有一种相对简单的方法来实现我想要的?
我使用以下python代码:
import os
import fileinput
dire = "directory"
# function for converting csv files to txt
def csv_to_txt(names, txtfilename):
# remove existing txt file
if os.path.exists(dire + txtfilename + ".txt"):
os.remove(dire + txtfilename + ".txt")
# open the include file
includefile = open(dire + txtfilename + ".txt", "a")
# handle the csv files and convert to txt
with open(names, "a+") as input_file:
lines = [line.split(",", 2) for line in input_file.readlines()]
print lines
text_list = [" ".join(line) for line in lines]
for line in text_list:
includefile.write(line)
includefile.close()
csv_to_txt(dire + "01.csv", "nameofoutputfile")
for line in fileinput.FileInput(dire + "nameofoutputfile" + ".txt",inplace=1):
line = line.replace('"','')
line = line.replace(',',' ')
【问题讨论】:
-
抱歉,我看不出你想要的和你现在拥有的有什么区别。
-
在这里,您的实际和预期结果都相同。可能是你输入错误了
-
你用什么代码来写你的txt文件?
-
嗨,Allen 和 Chanda,我更新了表格,以便您可以看到我所指的内容。另外,我按照pinggui的要求添加了代码。
-
如果您打开 csv 文件(逗号分隔值),您将看到由逗号分隔的值,而不是空格。
标签: python csv text-files