使用python更改CSV文件

时间:2018-12-12 05:11:22

标签: python csv

使用一个python脚本,我试图通过一个键将字符串更改为整数(即​​Male = 0和Female = 1)来更改CSV文件。但是,当我使用第一个功能写入CSV并使用第二个功能再次写入CSV时,它将覆盖我已经进行的更改。解决方案?还是有更好的读写CSV文件的方法?

{{1}}

2 个答案:

答案 0 :(得分:3)

您可以使用Pandas。这是一个功能强大的库,您只需几行即可完成

import pandas as pd

csv_file = pd.read_csv("information.csv")

# This opens the CSV file and now you can make changes here itself
# I will assume that your column 1 is called 'Gender' and column 2 is called 'Pets'

csv_file.loc[csv_file['Gender'] == 'Male','Gender'] = 0
csv_file.loc[csv_file['Gender'] == 'Female','Gender'] = 1

# Change for pets too

csv_file['Temporary_Pets_Column'] = 2
csv_file.loc[csv_file['Pets'] == 'Cat','Temporary_Pets_Column'] = 0
csv_file.loc[csv_file['Pets'] == 'Dog','Temporary_Pets_Column'] = 1

# Overwrite the pet's column with the temporary column.

csv_file['Pets'] = csv_file.pop('Temporary_Pets_Column')

# Save your csv file

csv_file.to_csv("updated_information.csv",index=False)

答案 1 :(得分:0)

只需以附加模式打开文件:

open('updated_version.csv', 'a', encoding ='utf-8', newline ='') 

来自文档:

``a''   Open for writing.  The file is created if it does not exist.  The
         stream is positioned at the end of the file.  Subsequent writes
         to the file will always end up at the then current end of file,
         irrespective of any intervening fseek(3) or similar.

 ``a+''  Open for reading and writing.  The file is created if it does not
         exist.  The stream is positioned at the end of the file.  Subse-
         quent writes to the file will always end up at the then current
         end of file, irrespective of any intervening fseek(3) or similar.