[英]how to delete the annoying data in the csv file
我想在我的csv文件中删除一些字符串(“ Description”“ This is a Simulation”),并且我也想删除数据中的一些“ =”和数据末尾的“,”。 该文件如下所示
"time","student","items"
="09:00:00","Tim","apple",
="09:00:10","Jason","orange",
"09:10:10","Emily","grape",
"09:22:10","Ivy","kiwi",
"Description"
"This is a simulation"
我尝试过.pop()。 它没有用
ff= []
import csv
with open('file.csv') as f:
for row in csv.DictReader(f):
row.replace(',','')
ff.append(row)
我想得到这样的:
"time","student","items"
"09:00:00","Tim","apple"
"09:00:10","Jason","orange"
"09:10:10","Emily","grape"
"09:22:10","Ivy","kiwi"
您可能希望将文件读取为原始文本文件而不是csv,以便您更轻松地执行字符串操作。
编辑:我假设tmp
是CSV文件的路径,而<list data>
是由csv.DictReader
生成的字典列表。 然后,您可以通过执行2个主要步骤来编写convert(tmp)
。 一种是将文件重新格式化为临时文件,另一种是使用csv.DictReader
将临时文件读入字典数据列表。 读取完数据后,将使用os
模块删除临时文件:
import csv
import os
def convert(tmp):
new_lines = []
temp_file = tmp + '.tmp'
with open(tmp) as fd:
for line in fd:
# remove new line characters
line = line.replace('\n', '').replace('\r', '')
# delete string
line = line.replace('=', '').replace('"Description"', '').replace('"This is a simulation"', '')
# don't add empty string
if line.strip() == '':
continue
# remove last line commas
if line[-1] == ',':
line = line[:-1]
new_lines.append(line)
# write formatted data to temporary csv file
with open(temp_file, 'w') as fd:
fd.write('\n'.join(new_lines))
# get list data
ff = None
with open(temp_file) as f:
ff = list(csv.DictReader(f))
# delete temporary file
os.remove(temp_file)
return ff
print convert('./file.csv')
大多数情况下利用内置的str
方法,并假设第一行始终是有效的标题行。
ff = []
with open('file.csv') as f:
for row in f:
# strip empty lines, and head/tail = ,
line = row.strip().strip('=').strip(',')
# skip empty lines
if not line:
continue
# assume first row is always a valid header row
# split by comma to see if it matches header row
if not len(ff) or (len(line.split(',')) == len(ff[0].split(','))):
ff.append(line)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.