我可以将数据更改为小写并删除所有标点符号,但在将更正后的数据保存到 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 文件的操作内容保存到第二个文件中。
关于python - 使用python保存CSV文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47122932/