1

我正在尝试使用 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 = []
4

1 回答 1

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])
于 2013-04-29T13:44:39.967 回答