我正在尝试使用python替换CSV文件中字段名称(或第一行)中的特殊字符。有很多问题与特殊字符密切相关,但我似乎无法找到第一行的任何内容。我在整个文档中替换了它们的脚本,但我只想让它在第一行中完成。我想如果我使用readline而不是readlines,它会工作,但这只会让大部分文件消失。任何帮助,将不胜感激。我的代码如下。
import os, sys, csv
lines = []
with open('C:/Characters.csv', 'r') as input:
lines = input.readlines()
conversion = '-"/.$'
newtext = '_'
outputLines = []
for line in lines:
temp = line[:]
for c in conversion:
temp = temp.replace(c, newtext)
outputLines.append(temp)
with open('C:/Characters_out.csv', 'w') as output:
for line in outputLines:
output.write(line + "\n")lines = []
答案 0 :(得分:1)
您只需要调整lines
列表中的第一行,无需迭代所有这些行,甚至可以复制到新列表中:
import csv
lines = []
with open('C:/Characters.csv', 'r') as input:
lines = input.readlines()
conversion = '-"/.$'
newtext = '_'
for c in conversion:
lines[0] = lines[0].replace(c, new_text)
with open('C:/Characters_out.csv', 'w') as output:
for line in lines:
output.write(line + "\n")
您甚至可以在没有lines
数组的情况下执行此操作:
import csv
input = open('C:/Characters.csv', 'r')
output = open('C:/Characters_out.csv', 'w')
conversion = '-"/.$'
newtext = '_'
index = 0
for line in input:
if index == 0:
for c in conversion:
line = line.replace(c, new_text)
output.write(line + "\n")
index += 1
您还可以使用正则表达式进行转换:
import re
lines[0] = re.sub(r'[-"/\.$]', '_', lines[0])