파이썬

[python] txt 파일 읽고 수정하기

Heeyeon Choi 2023. 8. 10. 17:33
728x90
import os
import shutil
import json

rootpath = "/hdd/street_obstacle/train/"

file_lst = os.listdir(rootpath)

for file in file_lst:
    if file.endswith(".txt") :
        edited_lines =""
        with open (rootpath+file) as f : 
            for t in f.readlines():
                string = t.split(' ')
                ans = float(string[0])
                ans = int(ans) -1 
                ans = str(ans)
                edited_lines =edited_lines+ ans
                for i in range(len(string)-1):
                    edited_lines = edited_lines+' ' + string[i+1]    
                
        with open (rootpath+file,"w") as f : 
             f.write(edited_lines)
                            
        f.close()​
edited_lines =edited_lines+ ans
      for i in range(len(string)-1):
           edited_lines = edited_lines+' ' + string[i+1]

생각한 것만큼 쉽지 않았습니다... txt 파일을 작성할 때는 쉬웠는데 수정하려니까 어려웠습니다

그래서 그 팁을 공유드리고자 합니다.

 

파이썬에서 우선 txt 파일을 읽기모드로 불러옵니다.

if file.endswith(".txt") :
        edited_lines =""
        with open (rootpath+file) as f : 
            for t in f.readlines():
                string = t.split(' ')

- 만약에, 해당 폴더에 .txt로 끝나는 파일이 있다면, 검사하도록 구현했습니다.

- f.readlines() 를 통해 파일의 내용을 읽어올 수 있습니다.

- 파일의 내용을 띄어쓰기 단위로 string 배열에 저장했습니다.

 

바꿀 내용을 포함하여 원래 내용에 계속해서 string에 더해줍니다. 

edited_lines =edited_lines+ ans
                for i in range(len(string)-1):
                    edited_lines = edited_lines+' ' + string[i+1]

저는 ans이라는 내용을 바꿨습니다.

 

이제는 파일을 쓰기 모드로 열어줍니다.

with open (rootpath+file,"w") as f : 
             f.write(edited_lines)

 

 

전체 코드를 보면 다음과 같습니다.

import os
import shutil
import json

rootpath = "/hdd/street_obstacle/train/"

file_lst = os.listdir(rootpath)

for file in file_lst:
    if file.endswith(".txt") :
        edited_lines =""
        with open (rootpath+file) as f : 
            for t in f.readlines():
                string = t.split(' ')
                ans = float(string[0])
                ans = int(ans) -1 
                ans = str(ans)
                edited_lines =edited_lines+ ans
                for i in range(len(string)-1):
                    edited_lines = edited_lines+' ' + string[i+1]    
                
        with open (rootpath+file,"w") as f : 
             f.write(edited_lines)
                            
        f.close()
728x90