python读取csv文件指定行并另存为csv文件
【代码】python读取csv文件指定行并另存为csv文件。
·
一、筛选某个属性的行,并另存为指定csv文件
def select_rows(input_file, output_file, selected_rows):
selected_data = []
with open(input_file, 'r', newline='') as file:
reader = csv.reader(file)
for i in reader:
# i[2]表示第三列的属性值等于selected_rows的话进行保存
if i[2] == selected_rows:
selected_data.append(i)
print(i)
# 新建文件并保存
# "a":–append模式,将新数据加到文件末尾,不会擦除现存的同名文件的内容
# "w":–write模式,写入时会覆盖之前文件的内容
with open(output_file, 'a', newline='') as file:
writer = csv.writer(file)
writer.writerows(selected_data)
二、根据行号读取前多少行
def selet_part(filePath, partFilePath):
# 读取原始CSV文件
df = pd.read_csv(filePath, low_memory=False)
# 提取部分行数据,例如前10行
partial_df = df.head(10)
# 将部分行数据保存为新的CSV文件
partial_df.to_csv(partFilePath, index=False)
更多推荐



所有评论(0)