문자열 바꾸기 작업을 수행하는 입력 파일이 있습니다.바꾸기 후 CSV에 쓸 수 없습니다.
셀별로 파일을 읽고 문자열을 바꾼 다음 새 CSV 파일에 다시 씁니다.
input_file = open('/Users/tcssig/Desktop/unstacked2.csv', 'r', encoding='utf-8')
output_file = open('/Users/tcssig/Desktop/unstacked3.csv', 'w', encoding='utf-8')
writer = csv.writer(output_file , delimiter=' ')
reader = csv.reader(input_file)
for row in reader:
for string in row:
data = [string.replace('read','write')]
print(data)
writer.writerow(data)
위의 코드는 정상적으로 실행되지만 빈 출력 파일이 표시됩니다.
Example of data :
reading reading reading reading
interval 0 1 2 3
who axis
Mikael X 0 10 20 30
Mikael Y 50 40 30 20
Mikael Z 100 90 80 70
Mike X 0 0.1 0.2 0.3
Mike Y 0.5 0.4 0.3 0.2
마이크 Z 1 0.9 0.8 0.7
내가 무슨 말이냐?
들여 쓰기를 수정하십시오. 어떤 코드가'for string in row :'블록에 들어가는지는 명확하지 않습니다. 또한 명확하게하기 위해 각 셀을 별도의 행으로 변환하려고합니까 아니면 셀의 값을 바꿉니 까? – ShadowRanger
파일을 자동으로 닫으려면 ['with'] (https://docs.python.org/2/reference/compound_stmts.html#the-with-statement) 문을 사용하십시오. – martineau
@scott, 위의 데이터 예제를 추가했습니다. – Sarang