在不知道文本的情况下替换CSV文件中的特定文本

时间:2015-06-02 11:49:50

标签: python file python-2.7 text

我需要从文本文件中替换特定值,而不知道要替换的字符串的值。我所知道的是行号,以及该行中必须替换的值的位置。这必须使用Python 2.7

完成 例如,文件是这样的:

a,b,c,s,d,f
s,d,f,g,d,f
a,d,s,f,g,r
a,s,d,f,e,c

我的代码是这样的:

point_file = open(pointfile,'r+')
read_lines = point_file.readlines()
arr1 = []
for i in range(len(read_lines)):
    arr1.append(read_lines[i])

现在我需要更换

arr1[3].split(',')[3]

怎么做?

修改

我不希望使用临时副本文件来实现此目的,然后覆盖现有文件。我需要编辑值到位 现有文件。

3 个答案:

答案 0 :(得分:0)

好的,所以我假设字段可以有任何值(或者通过巧妙的替换技巧可以大大缩短以下内容。)

from __future__ import print_function

target = (3, 3) # Coordinates of the replaced value
new_val = 'X'   # New value for the replaced cells
with open('src.txt') as f_src:
    data = f_src.read().strip()

table = [line.split(',') for line in data.split('\n')]
old_val = table[target[0]][target[1]]
new_data = '\n'.join(
                ','.join(
                    new_val if cell == old_val else cell
                    for cell in row)
                for row in table)

with open('tgt.txt', 'w') as f_tgt:
    print(new_data, file=f_tgt)

我的测试src.txt

a,b,c,s,d,f
s,d,f,g,d,f
a,d,s,f,g,r
a,s,d,f,e,c

我的输出tgt.txt

a,b,c,s,d,X
s,d,X,g,d,X
a,d,s,X,g,r
a,s,d,X,e,c

答案 1 :(得分:0)

试试这样。将数据作为csv文件读取,并将其转换为列表列表。然后,您可以更改所需索引[3][3]的值并回写给另一个csv

import csv

with open('indata.csv') as f:
    lines = [line for line in csv.reader(f)]

# change the required value
lines[3][3] = 'X'

with open('outdata.csv', 'w') as fout:
    csv.writer(fout).writerows(lines)

答案 2 :(得分:0)

[已解决]事实证明,如果不编写整个文件,就无法编辑文件的某个特定实例。如果我要在同一个文件中保存大量数据,这可能会占用大量内存。因此,我将文件中的保存数据替换为数组中的数据。