我想在我的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"
答案 0 :(得分:1)
您可能希望将文件读取为原始文本文件,而不是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')
答案 1 :(得分:0)
大多数情况下都利用内置的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)
答案 2 :(得分:0)
尝试一下:
# Reading the file contents and storing it in a variable
file_data = open('file.csv', 'r').read()
# String Manipulation to get your desired format
file_data = file_data.replace("=", "").replace("Description", "").replace("This is a simulation", "").replace(",\n\n","\n\n")[:-7]
# Writing formatted text back to your csv file
f = open('file.csv','w').write(file_data)
操作后file.csv :-
"time","student","items"
"09:00:00","Tim","apple"
"09:00:10","Jason","orange"
"09:10:10","Emily","grape"
"09:22:10","Ivy","kiwi"