python中txt转成csv_python - 将csv转换为txt而不会丢失列对齐

我已打开的.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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值