我想用python将多个csv文件转换为txt而不丢失列对齐方式。在
csv文件的示例以逗号分隔,没有空格或制表符,如下所示:
"Products" "Technologies" Region1 Region2 Region3
Prod1 Tech1 16 0 12
Prod2 Tech2 0 12 22
Prod3 Tech3 22 0 36
但使用我的脚本,我最终得出以下结论:
^{pr2}$分隔符的选择是任意的。考虑到包含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(',',' ')
CSV文件没有格式或对齐信息,它只是用逗号分隔的数据。通常是表处理器的工作来渲染csv。在
要将文件读入列表或字典,请使用csv标准模块。为了获得最佳打印效果,请使用PrettyTable或PTable forkhttps://pypi.python.org/pypi/PTable/0.9.0。其他工具是https://pypi.python.org/pypi/tabulate或texttable https://oneau.wordpress.com/2010/05/30/simple-formatted-tables-in-python-with-texttable,https://pypi.python.org/pypi/beautifultable/。在
带PTable
对于一些简单的表,简单的snippet也可以。在
就我个人而言,当我不得不打印出一个表而不需要额外的包时,我会使用一些特别的字符串格式,但是包通常更愚蠢的证明,支持很多选项,所以如果你要处理很多表,这可能是值得的。在
Prettytable似乎是最受欢迎的(好名字)。 tablate claims比大多数漂亮的表打印机性能更好,节省asciitable(现在astropy.io.ascii,所以可能有点过火了,除非你是个火箭科学家)
我做了一个程序,可以打开一个.csv,并且(希望)完全符合您的要求:
在此之前:
^{pr2}$之后:
相关问题 更多 >
编程相关推荐