2015-02-09 56 views
-3

我有这样的数据集:的Python - 在CSV行的替换值文件

['XXXX-XXXX', '0'] 
['XXXX-XXXX', '0'] 
['XXXX-XXXX', '0'] 
['XXXX-XXXX', '0'] 
['XXXX-XXXX', '0'] 
['XXXX-XXXX', '0'] 
['XXXX-XXXX', '0'] 
['XXXX-XXXX', '0'] 

基本上我想“0”递增地改变所述第二字段为“1”的程序的每次运行之后,像这个:

['XXXX-XXXX', '1'] # first run 
['XXXX-XXXX', '0'] 
['XXXX-XXXX', '0'] 
['XXXX-XXXX', '0'] 
['XXXX-XXXX', '0'] 
['XXXX-XXXX', '0'] 
['XXXX-XXXX', '0'] 
['XXXX-XXXX', '0'] 

['XXXX-XXXX', '1'] # second run 
['XXXX-XXXX', '1'] 
['XXXX-XXXX', '0'] 
['XXXX-XXXX', '0'] 
['XXXX-XXXX', '0'] 
['XXXX-XXXX', '0'] 
['XXXX-XXXX', '0'] 
['XXXX-XXXX', '0'] 

['XXXX-XXXX', '1'] # eigth run 
['XXXX-XXXX', '1'] 
['XXXX-XXXX', '1'] 
['XXXX-XXXX', '1'] 
['XXXX-XXXX', '1'] 
['XXXX-XXXX', '1'] 
['XXXX-XXXX', '1'] 
['XXXX-XXXX', '1'] 

该.csv文件应该直接编辑。我对如何解决这个问题没有丝毫的想法,我是一个蟒蛇新手..

+0

找到的第一个0,更改为1,那么只写线条 – 2015-02-09 18:30:07

+2

的其余部分如果你还没有丝毫的想法如何处理问题,那么您在这里询问时没有正确使用Stack Overflow。这是为了当你中途遇到问题而陷入困境时。你刚刚开始。 – 2015-02-09 18:30:11

+0

这可能会帮助你http://stackoverflow.com/questions/11033590/change-specific-value-in-csv-file-via-python – 2015-02-09 18:40:02

回答

0

这里有东西让你朝正确的方向前进。

with open('path/to/filename') as filehandler_name: 
    # this is how you open a file for reading 

with open('path/to/filename', 'w') as filehandler_name: 
    # this is how you open a file for (over)writing 
    # note the 'w' argument to the open built-in 

import csv 
# this is the module that handles csv files 

reader = csv.reader(filehandler_name) 
# this is how you create a csv.reader object 
writer = csv.writer(filehandler_name) 
# this is how you create a csv.writer object 

for line in reader: 
    # this is how you read a csv.reader object line by line 
    # each line is effectively a list of the fields in that line 
    # of the file. 
    # # XXXX-XXXX, 0 --> ['XXXX-XXXX', '0'] 

对于小文件,你可以这样做:

import csv 

with open('path/to/filename') as inf: 
    reader = csv.reader(inf.readlines()) 

with open('path/to/filename', 'w') as outf: 
    writer = csv.writer(outf) 
    for line in reader: 
     if line[1] == '0': 
      writer.writerow([line[0], '1') 
      break 
     else: 
      writer.writerow(line) 
    writer.writerows(reader) 

对于大文件,因为它是拉动整个文件到内存一旦inf.readlines会杀了你的内存分配,你应该做的事情像:

import csv, os 

with open('path/to/filename') as inf, open('path/to/filename_temp', 'w') as outf: 
    reader = csv.reader(inf) 
    writer = csv.writer(outf) 
    for line in reader: 
     if line[1] == '0': 
      ... 
     ... # as above 

os.remove('path/to/filename') 
os.rename('path/to/filename_temp', 'path/to/filename') 
+0

非常感谢你!它工作完美。 – 2015-02-09 19:22:11