2017-11-16 5 views
0

초보자이며 짧은 코드 문제가 있습니다. CSV의 문자열을 다른 문자열로 바꾸고 싶고 새 이름을 사용하여 csv를 새로 써야합니다. 문자열은 쉼표로 구분됩니다.Python : CSV 파일의 문자열 바꾸기

import csv 

f = open('C:\\User\\Desktop\\Replace_Test\\Testreplace.csv') 
csv_f = csv.reader(f) 

g = open('C:\\Users\\Desktop\\Replace_Test\\Testreplace.csv') 
csv_g = csv.writer(g) 


findlist = ['The String, that should replaced'] 
replacelist = ['The string that should replace the old striong'] 


#the function ?: 
def findReplace(find,replace): 
s = f.read() 
for item, replacement in zip(findlist,replacelist): 
s = s.replace(item,replacement) 
g.write(s) 

for row in csv_f: 
print(row) 

f.close() 
g.close() 
+2

들여 쓰기를 교정 해주십시오. –

답변

0

당신은 정규식 패키지 re하여이 작업을 수행 할 수 있습니다

내 코드는 재앙이다. 또한 with을 사용하면 파일을 닫지 않아도되므로 도움이됩니다.

편집 : 정확한 문자열과 일치하므로 대소 문자를 구별합니다. 만약 당신이 그것을 원하지 않는다면 대체 할 문자열을 찾기 위해 실제 정규 표현식을 사용해야 할 것입니다. re.sub() 호출에서 find_strr'your_regex_here'으로 바꾸면됩니다.

import re 

# open your csv and read as a text string 
with open(my_csv_path, 'r') as f: 
    my_csv_text = f.read() 

find_str = 'The String, that should replaced' 
replace_str = 'The string that should replace the old striong' 

# substitute 
new_csv_str = re.sub(find_str, replace_str, my_csv_text) 

# open new file and save 
new_csv_path = './my_new_csv.csv' # or whatever path and name you want 
with open(new_csv_path, 'w') as f: 
    f.write(new_csv_str)