简体   繁体   English

从CSV解析列,并将文本文件中的值替换为新值

[英]Parsing column from CSV and replace a value in text file with the new value

I have one CSV file, and I want to extract the first column of it. 我有一个CSV文件,我想提取它的第一列。 My CSV file is like this: 我的CSV文件是这样的:

Device ID;SysName;Entry address(es);IPv4 address;Platform;Interface;Port ID (outgoing port);Holdtime
PE1-PCS-RANCAGUA;;;192.168.203.153;cisco CISCO7606 Capabilities  Router Switch IGMP;TenGigE0/5/0/1;TenGigabitEthernet3/3;128 sec
P2-CORE-VALPO.cisco.com;P2-CORE-VALPO.cisco.com;;200.72.146.220;cisco CRS Capabilities  Router;TenGigE0/5/0/0;TenGigE0/5/0/4;128 sec
PE2-CONCE;;;172.31.232.42;Cisco 7204VXR Capabilities  Router;GigabitEthernet0/0/0/14;GigabitEthernet0/3;153 sec
P1-CORE-CRS-CNT.entel.cl;P1-CORE-CRS-CNT.entel.cl;;200.72.146.49;cisco CRS Capabilities  Router;TenGigE0/5/0/0;TenGigE0/1/0/6;164 sec

For that purpose I use the following code that I saw here: 为此,我使用在这里看到的以下代码:

import csv

makes = []
with open('csvoutput/topologia.csv', 'rb') as f:
    reader = csv.reader(f)
#    next(reader) # Ignore first row

    for row in reader:
        makes.append(row[0])

print makes

Then I want to replace into a textfile a particular value for each one of the values of the first column and save it as a new file. 然后,我想将第一列中每个值的特定值替换为文本文件,并将其另存为新文件。

Original textfile: 原始文本文件:

    PLANNED.IMPACTO_ID = IMPACTO.ID   AND 
    PLANNED.ESTADOS_ID = ESTADOS_PLANNED.ID   AND 
    TP_CLASIFICACION.ID = TP_DATA.ID_TP_CLASIFICACION   AND 
    TP_DATA.PLANNED_ID = PLANNED.ID AND 
    PLANNED.FECHA_FIN >= CURDATE() - INTERVAL 1 DAY AND 
    PLANNED.DESCRIPCION LIKE '%P1-CORE-CHILLAN%’;

Expected output: 预期产量:

    PLANNED.IMPACTO_ID = IMPACTO.ID   AND 
    PLANNED.ESTADOS_ID = ESTADOS_PLANNED.ID   AND 
    TP_CLASIFICACION.ID = TP_DATA.ID_TP_CLASIFICACION   AND 
    TP_DATA.PLANNED_ID = PLANNED.ID AND 
    PLANNED.FECHA_FIN >= CURDATE() - INTERVAL 1 DAY AND 
    PLANNED.DESCRIPCION LIKE 'FIRST_COLUMN_VALUE’;

And so on for every value in the first column, and save it as a separate file. 对于第一列中的每个值,依此类推,然后将其保存为单独的文件。

How can I do this? 我怎样才能做到这一点? Thank you very much for your help. 非常感谢您的帮助。

You could just read the file, apply changes, and write the file back again. 您可以只读取文件,应用更改并再次写回文件。 There is no efficient way to edit a file (inserting characters is not efficiently possible), you can only rewrite it. 没有有效的方法来编辑文件(不可能有效地插入字符),只能重写它。

If your file is going to be big, you should not keep the whole table in memory. 如果文件很大,则不应将整个表保留在内存中。

import csv

makes = []
with open('csvoutput/topologia.csv', 'rb') as f:
  reader = csv.reader(f)
  for row in reader:
      makes.append(row)

# Apply changes in makes

with open('csvoutput/topologia.csv', 'wb') as f:
  writer = csv.writer(f)
  writer.writerows(makes);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM