如何在python中从CSV文件中删除空行?
晚上好!我目前正在使用Python3脚本创建一个包含指定数据列的CSV文件。我真的快完成了,但我遇到了一个无法克服的问题 基本上,我尝试将两个列中的两个值(浮动)相加,并将它们附加到另一列中;然而,当程序运行到空行(字符串)中时,一切都会失败。据我所知,将整个csv文件转换为浮点是不可能的,所以我决定删除这些空行。。。我该怎么做 此外,如果有人对更清洁的方法有任何建议,我将非常高兴听到 我的代码如下:如何在python中从CSV文件中删除空行?,python,python-3.x,csv,Python,Python 3.x,Csv,晚上好!我目前正在使用Python3脚本创建一个包含指定数据列的CSV文件。我真的快完成了,但我遇到了一个无法克服的问题 基本上,我尝试将两个列中的两个值(浮动)相加,并将它们附加到另一列中;然而,当程序运行到空行(字符串)中时,一切都会失败。据我所知,将整个csv文件转换为浮点是不可能的,所以我决定删除这些空行。。。我该怎么做 此外,如果有人对更清洁的方法有任何建议,我将非常高兴听到 我的代码如下: #! python3 # automatedReport.py - Reads and wri
#! python3
# automatedReport.py - Reads and writes a new CSV file with
# Campaign Name, Group Name, Raised from Apr 1st-Apr 30th Total,
# Donation from Apr 1st-Apr 30th Total, and Campaign Total Apr 1st-Apr 30th.
import csv, os, ctypes
MessageBox = ctypes.windll.user32.MessageBoxW
total = 0
# Find out whether or not campaign_monthly_report is present.
if os.path.isfile('campaign_monthly_report.csv'):
os.makedirs('automatedReport', exist_ok=True)
print('Organizing campaign_monthly_report.csv...')
#Read the CSV file.
with open('campaign_monthly_report.csv', 'r') as csv_file:
csv_reader = csv.DictReader(csv_file)
#Write out the CSV file.
with open(os.path.join('automatedReport', 'automated_campaign_monthly_report.csv'), 'w', newline='') as new_file:
fieldnames = ['Campaign Name','Group Name','Raised from Apr 1st-Apr 30th Total','Donation from Apr 1st-Apr 30th Total', 'Campaign Total Apr 1st-Apr 30th']
csv_writer = csv.DictWriter(new_file, fieldnames=fieldnames)
csv_writer.writeheader()
#Sloopy code, I know. I'm a bit new to this.
for line in csv_reader:
del line['Contact Name']
del line['Contact Phone']
del line['Contact Email']
del line['Sign Ups']
del line['Active Members']
del line['% Active Members']
del line['Raised upto Mar 31st 1st Time']
del line['Raised upto Mar 31st Everyday']
del line['Raised upto Mar 31st Total']
del line['Raised upto Mar 31st Target']
del line['Donation upto Mar 31st Group']
del line['Donation upto Mar 31st PF']
del line['Donation upto Mar 31st Total']
del line['Additional $ Applied upto Mar 31st']
del line['Raised from Apr 1st-Apr 30th 1st Time']
del line['Raised from Apr 1st-Apr 30th Everyday']
del line['Raised from Apr 1st-Apr 30th Target']
del line['Donation from Apr 1st-Apr 30th Group']
del line['Donation from Apr 1st-Apr 30th PF']
del line['Additional $ Applied from Apr 1st-Apr 30th Total']
del line['Date Joined']
total = float(line['Raised from Apr 1st-Apr 30th Total']) + float(line['Donation from Apr 1st-Apr 30th Total'])
csv_writer.writerow(line)
print (total)
MessageBox(None, 'Process Complete. Locate ouput in the automatedReport folder.', ' Success!', 0)
else:
MessageBox(None, 'campaign_monthly_report not found!', ' Error!', 0)
错误消息:
Traceback (most recent call last):
File "C:\Users\Mende\Desktop\Automated Campaign\automatedReport.py", line 51, in <module>
total = float(line['Raised from Apr 1st-Apr 30th Total']) + float(line['Donation from Apr 1st-Apr 30th Total'])
ValueError: could not convert string to float: >>>
回溯(最近一次呼叫最后一次):
文件“C:\Users\Mende\Desktop\Automated Campaign\automatedReport.py”,第51行,在
总计=浮动(第['行从4月1日至4月30日总计])+浮动(第['行从4月1日至4月30日总计]捐赠)
ValueError:无法将字符串转换为浮点值:>>>
csv模块只希望其文件是一个迭代器,在每次迭代时返回一行新行。定义一个迭代器来过滤掉空行是很简单的:
def no_blank(fd):
try:
while True:
line = next(fd)
if len(line.strip()) != 0:
yield line
except:
return
您可以使用它从原始文件对象中筛选出空行:
...
#Read the CSV file.
with open('campaign_monthly_report.csv', 'r') as csv_file:
csv_reader = csv.DictReader(no_blank(csv_file))
...
听说过熊猫吗?我看了一下,它似乎就是我想要的,但我希望有一种方法可以做到这一点,而无需下载外部库。没有办法吗?你的图书馆有限制吗?否则它很简单:
pip安装pandas
,它可以在2或3行代码中完成您想要的操作。在任何情况下,我都不知道您正在使用的软件包,因此我无法帮助您。请定义“kaput”,并向我们显示错误消息和它出现的行号。