python在不丢失列对齐的情况下将csv转换为txt

2024-10-04 11:28:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用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(',',' ')

Tags: 文件csvtoinimporttxtforos
2条回答

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-texttablehttps://pypi.python.org/pypi/beautifultable/。在

带PTable

   from prettytable import from_csv
   fp = open("myfile.csv", "r")
   mytable = from_csv(fp)
   fp.close()
   mytable.border = False
   print mytable.get_string()

对于一些简单的表,简单的snippet也可以。在

就我个人而言,当我不得不打印出一个表而不需要额外的包时,我会使用一些特别的字符串格式,但是包通常更愚蠢的证明,支持很多选项,所以如果你要处理很多表,这可能是值得的。在


Prettytable似乎是最受欢迎的(好名字)。 tablate claims比大多数漂亮的表打印机性能更好,节省asciitable(现在astropy.io.ascii,所以可能有点过火了,除非你是个火箭科学家)

我做了一个程序,可以打开一个.csv,并且(希望)完全符合您的要求:

import tkinter as tk
from tkinter import filedialog
import os
import csv as csv_package

def fileopen():
    GUI=tk.Tk()
    filepath=filedialog.askopenfilename(parent=GUI,
                                        title='Select file')
    (GUI).destroy()
    return (filepath)

filepath = fileopen()
filepath = os.path.normpath(filepath)
data = []
with open(filepath) as fp:
    reader = csv_package.reader(fp, skipinitialspace=True)
    for row in reader:
        data.append(row)

#make spreadsheet rows consistent length, based on longest row
max_len_row = len(max(data,key=len))
for row in data:
    if len(row) < max_len_row:
        append_number = max_len_row - len(row)
        for i in range(append_number):
            row.append('')

#create dictionary of number of columns
longest = {}
for times in range(len(data[0])):
    longest [times] = 0

#get longest entry for each column
for sublist_index,sublist in enumerate(data):
    for column_index,element in enumerate(sublist):
        if longest [column_index] < len(element):
            longest [column_index] = len(element)

#make each column as long as the longest entry
for sublist_index,sublist in enumerate(data):
    for column_index,element in enumerate(sublist):
        if len(element) < longest [column_index]:
            amount_to_append = longest [column_index] - len(element)
            data [sublist_index][column_index] += (' ' * amount_to_append)

with open(filepath, 'w', newline='') as csvfile:
    writer = csv_package.writer(csvfile)
    for row in data:
        writer.writerow(row)

path, ext = os.path.splitext(filepath)
os.rename(filepath, path + '.txt')

在此之前:

^{pr2}$

之后:

Products,Technologies,Region1,Region2,Region3
Prod1   ,Tech1       ,16     ,0      ,12     
Prod2   ,Tech2       ,0      ,12     ,22     
Prod3   ,Tech3       ,22     ,0      ,36 

相关问题 更多 >