pythoncsv数据怎么设置_如何使用python对齐CSV文件中的数据

I'm using following code to write data into csv file:

filename = "DETAILS.csv"

f = open(filename, "a")

f.write(

school_name + "," + affiliation_no + "," + state + "," + district + ","

+ postal_address + "," + phone_no + "," + email_id + "," + web_site + ","

+ year_of_foundation + "," + date_of_opening + "," + name_of_principal + ","

+ status_of_school + "," + type_of_affiliation + "," + affiliation_period_from + ","

+ affiliation_period_to + "," + name_of_trust_society_managing_committee + "\n")

f.close()

I'm getting the output in this format:

The columns and data are not aligned in csv file.I need one row per each entry. Can anyone help me fix it?

解决方案

As a general rule, when you work with CSV files, you shouldn't use the standard file operations, but use the writer and reader classes from the csv module. These classes take care of quotation marks and of the character used to separate the columns in your file (the comma , in your case). They also automatically handle numbers and strings correctly.

So, your code becomes this:

import csv

filename = "DETAILS.csv"

f = open(filename, "a")

# create a CSV writer object:

csvwriter = csv.writer(f)

# create a list of values that will be written to the file:

dat = [school_name, affiliation_no, state, district, postal_address,

phone_no, email_id, web_site, year_of_foundation, date_of_opening,

name_of_principal, status_of_school, type_of_affiliation,

affiliation_period_from, affiliation_period_to,

name_of_trust_society_managing_committee]

# write the list to the file, using ',' automatically to separate the

# columns:

csvwriter.writerow(dat)

f.close()

But this alone may not be enough to solve your issue. It looks as if the program that you use to open the CSV file encounters one or more characters that it can't interpret correctly. As pointed out by others, the offending characters may be the tabulator character \t or the linebreak character \n, but as you seem to refuse to paste some of the actual content of your file, there is no way of knowing that for sure.

However, you can use the following code to replace these characters by a space. The list comprehension handles both numbers and strings:

dat = [val.replace("\n", " ")

.replace("\t", " ") if type(val) is str else val for val in dat]

You can add this before the call to csvwriter.writerow(dat) in my code example to make sure that the problematic characters are removed before the row is written to the CSV file.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值