python - 使用python保存CSV文件

标签 python python-2.7 csv

我可以将数据更改为小写并删除所有标点符号,但在将更正后的数据保存到 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/

相关文章:

python - 检查用户是否具有 Pyramid (pylons 2)的权限?

python - 将输出文件添加到 Python 扩展

c - 在 C 中读取 CSV 文件

Python xlrd 通过日期转换将 Excel xlsx 解析为 csv

python - 为什么这个数字根功能不起作用?

python - Leetcode 21. 合并两个排序列表。努力理解解决方案的工作原理

python - "Global name not defined"错误

python - 使用 MongoDB 管理 Python 多处理

python - 将两位数整数转换为python列表中的一位数?

php - 使用 PHP/MySQL 导入 CSV 数据 - 完整示例