2017-04-05 50 views
0

我有一個標題行以下輸入文件: test_in.csvPython的CSV - 與指定的值替換任何列

LON,LAT,NUMBER,STREET,UNIT,CITY,DISTRICT,REGION,POSTCODE,ID,HASH 
-72.5708234,41.4155142,39,HICKORY LA,,,,,,,8a0df668e0d49b02 
-72.5647745,41.4160301,1213,KILLINGWORTH RD,,,,,,,b3ecaab86e476f46 

我需要與例如CITY指定字符串 替換任何列列的數據應當從「」到「MyCity」取代 我的代碼僅輸出報頭和第一行

蟒test_forcefld.py test_in.csv MyCity CITY out_test.csv

import csv 
import sys 

in_file_name = sys.argv[1] 
force_data = sys.argv[2] 
force_fld = sys.argv[3] 
out_file_name = sys.argv[4] 

# First read top row/header from input file 
fieldnames = [] 
for filename in [in_file_name]: 
    with open(filename, "rb") as f_in: 
    reader = csv.reader(f_in) 
    headers = next(reader) 
    for h in headers: 
     fieldnames.append(h) 
#print headers to output file 
with open(out_file_name, 'w') as fou: 
    dw = csv.DictWriter(fou, delimiter=',', fieldnames=fieldnames) 
    dw.writeheader() 

f_in2 = open(in_file_name, "rb") 
reader2 = csv.DictReader(f_in2) # Uses the field names in this file 
datarow = next(reader2) 
datarow[force_fld] = force_data 
with open(out_file_name, 'wa') as fou: 
    dw2 = csv.DictWriter(fou, delimiter=',', fieldnames=fieldnames) 
    dw2.writeheader() 
    dw2.writerow(data row) 

輸出顯示

LON,LAT,NUMBER,STREET,UNIT,CITY,DISTRICT,REGION,POSTCODE,ID,HASH 
-72.5708234,41.4155142,39,HICKORY LA,,MyCity,,,,,8a0df668e0d49b02 

回答

0

你的代碼是有點難以閱讀,但假設數據行是包含你的記錄一本字典:

在你的最後一排,改變

dw2.writerow(datarow) 

進入

dw2.writerows(datarow) 

當您處於這種狀態時,爲了簡明起見,您還應該考慮使用datarow.keys()作爲字段名。

0

這應該這樣做,你只需要pandas

import pandas as pd 
df = pd.read_csv(in_file_name, sep=',') 
df['CITY'].fillna('MyCity', inplace=True) 

,並保存它:

df.to_csv(out_file_name) 
0

你可以嘗試財產以後這樣纔能有你需要的文件:

我假設你的輸入文件叫做f_input.txt,你的輸出文件叫做f_output.txt

data = list(k.rstrip().split(',') for k in open("f_input.txt", 'r')) 

with open("f_output.txt", 'a+') as f: 
    f.write(",".join(data[0]) + '\n') 
    for k in data[1:]: 
     # Modify the positions of k[:n] + your data + k[n+1] 
     # if you need to handle another position 
     f.write(",".join(k[:6]) + "MyCity" + ",".join(k[7:]) + "\n") 
0

這個工作到底:

import csv 
import sys 

in_file_name = sys.argv[1] 
force_data = sys.argv[2] 
force_fld = sys.argv[3] 
out_file_name = sys.argv[4] 

# First read top row/header from input file 
fieldnames = [] 
for filename in [in_file_name]: 
    with open(filename, "rb") as f_in: 
    reader = csv.reader(f_in) 
    headers = next(reader) 
    for h in headers: 
     fieldnames.append(h) 

f_in2 = open(in_file_name, "r") 
#print headers to output file 
fou = open(out_file_name, 'wa') 
dw = csv.DictWriter(fou, delimiter=',', fieldnames=fieldnames) 
dw.writeheader() 
reader2 = csv.DictReader(f_in2) # Uses the field names in this file 
for row in reader2: 
    row[force_fld] = force_data 
    dw2 = csv.DictWriter(fou, delimiter=',', fieldnames=fieldnames) 
    dw2.writerow(row)