2015-02-09 54 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