我正在制作一个CSV过滤程序,该程序将多个CSV文件过滤为1个CSV文件。现在,我的程序正在选择特定记录,并使用CSV文件中的日期时间做一些技巧。现在一切正常。
现在,我想向csv文件添加标头,因为它现在没有任何标头。我尝试使用熊猫来做到这一点(请参阅最后几行代码),但收到以下错误:writer.writerow(encoded_labels) UnsupportedOperation: not writable
my_set = {'AA', 'BB', 'CC'}
def filter_row(r):
condition_1 = set(row).intersection(my_set) #<-- selecting the specific words to filter on
return condition_1
def timestamp_to_columns(timestamp):
date_object = datetime.datetime.fromisoformat(timestamp)
time_tuple = date_object.timetuple()
return [*time_tuple[:6], int(date_object.utcoffset().seconds / 3600)]
def update_row(row):
return [
*timestamp_to_columns(row[0]),
*row[1:4], # the other columns we need
*timestamp_to_columns(row[6]),
]
for file in os.listdir(destination):
file_path = os.path.join(destination, file)
with open(file_path, 'r') as my_file, open('output.txt', 'w') as outer:
reader = csv.reader(my_file, delimiter = ',')
next(reader)
writer = csv.writer(outer, delimiter = '\t')
for row in reader:
if filter_row(row):
writer.writerow(update_row(row))
df = pd.read_csv(my_file, names = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']) #<--- adding the headers
df.to_csv(my_file, index=False)
我真的希望解决这个问题,我的目标是在update_now
函数中添加代码。