Skip to main content
 首页 » 编程设计

python之使用 python 保存 CSV 文件

2024年10月01日15落叶无声

我可以将数据更改为小写并删除所有标点符号,但我无法将更正后的数据保存到 CSV 文件中。

import csv 
import re 
import os 
 
input_file=raw_input("Name of the CSV file:") 
output_file=raw_input("Output Name:") 
 
 
reg_test=input_file 
result = '' 
 
with open(input_file,'r') as csvfile: 
  with open(output_file,'w') as csv_out_file: 
  filereader = csv.reader(csvfile) 
  filewriter =csv.writer(csv_out_file) 
  for row in filereader: 
     row = re.sub('[^A-Za-z0-9]+', '', str(row)) 
     result += row + ',' 
 
lower = (result).lower() 
csvfile.close() 
csv_out_file.close() 

请您参考如下方法:

您不必关闭文件,这是在 with 语句的上下文结束后自动完成的,您必须在创建 csv.writer 后实际写一些东西,例如使用 writerow:

import csv 
import re 
 
input_file = 'in.csv' 
output_file = 'out.csv' 
 
with open(input_file, 'r') as csvfile, open(output_file, 'w') as csv_out_file: 
    filereader = csv.reader(csvfile) 
    filewriter = csv.writer(csv_out_file) 
    for row in filereader: 
        new_row = re.sub('[^A-Za-z0-9]+', '', str(row))  # manipulate the row 
        filewriter.writerow([new_row.lower()])  # write the new row to the out file 
 
# the files are closed automatically after the context of the with statement is over 

这会将第一个 csv 文件的操作内容保存到第二个。