我在输出csv文件中写回我想要的值时遇到了一些问题。我的目的是获取csv文件的值并更改那些等于'从不工作'或者'无薪'不工作'。我的代码成功实现了这一点,但是,它没有正确地将它写回csv文件,这意味着不会写回更改的值,但文件保持与原始文件相同。我做错了什么?
import csv
infile = open('income.csv','rb')
outfile = open('income-new.csv', 'wb')
def changeOccupation(cell):
if (cell.lower() == 'never-worked' or cell.lower() == 'without-pay'):
cell = 'Not-working'
print(cell)
#go trough each line of the file
for line in infile:
row = line.split(',')
for cell in row:
changeOccupation(cell)
#print(row)
outfile.write(','.join(row))
infile.close()
outfile.close()
答案 0 :(得分:2)
您需要重新调整新值并更改已更改的行包:
def changeOccupation(cell):
if (cell.lower() == 'never-worked' or cell.lower() == 'without-pay'):
return 'Not-working'
return cell
#go trough each line of the file
for line in infile:
row = line.split(',')
new_row = [changeOccupation(cell) for cell in row]
outfile.write(','.join(new_row))