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
'파이썬' 카테고리의 다른 글
[python] 카카오톡 API를 사용하여, 나에게 카카오톡 메시지 보내기 (4) | 2023.10.24 |
---|---|
[AI, python] AI HUB 데이터셋의 어노테이션(Annotation, label)을 darknet format으로 변환하기 (BBOX일 경우) (0) | 2023.08.16 |
[python] 폴더에서 jpg 파일만 옮기기 (0) | 2023.08.02 |
[python] 디렉터리 내에서 원하는 파일 개수만큼 옮기기 (0) | 2023.08.02 |
[파이썬] 디렉터리마다 파일 n개씩만 다른 폴더로 복사하기 (0) | 2023.04.05 |