【问题标题】:python - convert csv to txt without losing column alignmentpython - 将 csv 转换为 txt 而不会丢失列对齐
【发布时间】: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


【解决方案1】:

CSV 文件没有格式或对齐信息,它只是用逗号分隔的数据。通常,渲染 csv 是表格处理器的工作。

要将文件读入列表或字典,请使用 csv 标准模块。为了获得漂亮打印的最佳效果,请使用 PrettyTable 或 PTable fork https://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 似乎是最受欢迎的(好名字)。 制表claims 比大多数漂亮的台式打印机性能更好,保存 asciitable(现在是 astropy.io.ascii,所以可能有点矫枉过正,除非你是火箭科学家)

【讨论】:

  • 嗨,Serge,感谢您为我指明了正确的方向。这就是我一直在寻找的。​​span>
  • 任何时候,祝你好运。如果您觉得答案有帮助,请不要犹豫,点赞或接受它
【解决方案2】:

我制作了一个程序,它可以打开一个 .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')

之前:

"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 

【讨论】:

  • 您好 new_to_coding,感谢您在这里提供帮助。我也做了这项工作。
猜你喜欢
  • 1970-01-01
  • 2015-04-20
  • 2021-11-16
  • 2013-11-14
  • 2012-07-16
  • 1970-01-01
  • 2010-10-29
  • 2012-07-01
  • 2018-10-31
相关资源
最近更新 更多