2017-04-24 35 views
2

我想使用python將多個csv文件轉換爲txt,而不會丟失列對齊。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(',',' ') 
+0

對不起,我不明白你想要什麼和你現在有什麼不同。 – Allen

+0

在這裏,你的實際和預期的結果都是一樣的。可能是你輸入了錯誤的信息 –

+0

你用什麼代碼編寫你的txt文件? – pingul

回答

2

CSV文件進行無格式或對齊方式,它只是數據以逗號分隔。通常情況下,表處理器的工作是渲染csv。

要將文件讀入列表或字典,請使用csv標準模塊。爲了在漂亮打印中獲得最佳效果,請使用PrettyTable或PTable叉https://pypi.python.org/pypi/PTable/0.9.0。其他工具是https://pypi.python.org/pypi/tabulate或文字表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比最漂亮的表打印機更好的性能,節省ASCII表(現astropy.io.ascii,所以可能會有點矯枉過正,除非你是一個火箭科學家)

+0

嗨Serge, 謝謝你指點我在正確的方向。這是我正在尋找的。 –

+0

隨時好運。如果您發現答案有幫助,請立即投訴或接受 – Serge

0

我已打開的.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 
+0

嗨new_to_coding, 感謝您在此提供幫助。我也做了這項工作。 –

相關問題